package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.crm.service.executor.query.PublicPoolListQry;
import com.xbongbong.executor.query.CommonListQry;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DateTimeEnum;
import com.xbongbong.paas.enums.DateTypeEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.UnitEnum;
import com.xbongbong.paas.factory.OptionFactory;
import com.xbongbong.paas.factory.WebDataAnalysisFactory;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.handle.AbstractOptionHandle;
import com.xbongbong.paas.handle.AbstractWebDataAnalysisHandle;
import com.xbongbong.paas.handle.ProductAnalysisDataHandle;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataListSearchHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.ButtonExtraPojo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.ProductFieldPojo;
import com.xbongbong.paas.pojo.ShareConditionFormatPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.CoUserListDTO;
import com.xbongbong.paas.pojo.dto.ColumnSetListDTO;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ListGroupListDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.dto.SubFormListDTO;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.vo.ChildExpansionListVO;
import com.xbongbong.paas.pojo.vo.ColumnSetListVO;
import com.xbongbong.paas.pojo.vo.GroupListVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.UserAndDepartmentGetVO;
import com.xbongbong.paas.pojo.vo.UserFormPermissionVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.CallCenterCommonService;
import com.xbongbong.paas.service.CoUserService;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasCommentService;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.service.PaasListGroupService;
import com.xbongbong.paas.service.UserConfigService;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.pojo.PermissionTermsPojo;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.pro.applist.pojo.AppListFilterAttrPojo;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.applist.pojo.SelectOptionPojo;
import com.xbongbong.pro.applist.pojo.dto.ListAppSearchFilterDTO;
import com.xbongbong.pro.applist.pojo.vo.ListAppExtVO;
import com.xbongbong.pro.applist.pojo.vo.ListAppVO;
import com.xbongbong.pro.applist.pojo.vo.SearchFilterVO;
import com.xbongbong.pro.common.pojo.dto.WaitOutProductDTO;
import com.xbongbong.pro.common.pojo.vo.DimensionViewPoJo;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigHasBeenEnableDTO;
import com.xbongbong.pro.companyconfig.pojo.vo.CompanyConfigHasBeenEnableVO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.RangeScreenConstant;
import com.xbongbong.pro.detailtab.dto.DetailTabDataGetDTO;
import com.xbongbong.pro.detailtab.dto.OrderOnPinDTO;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.domain.entity.StockDateFilterEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.TimeTypeEnum;
import com.xbongbong.pro.enums.errorcodes.ApprovalErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessTypeErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CommuicatePlanErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProductErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PurchaseErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.StatisticsServicesErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ThirdPartyUsageErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.CRMMenuEnum;
import com.xbongbong.pro.enums.menu.enums.MultiDimensionViewEnum;
import com.xbongbong.pro.enums.permission.enums.ExportProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.form.pojo.dto.EsDataDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeListDTO;
import com.xbongbong.pro.listgroup.pojo.ListGroupVO;
import com.xbongbong.pro.paymenttask.pojo.dto.PaymentTaskExportDTO;
import com.xbongbong.pro.paymenttask.pojo.dto.PaymentTaskGetDTO;
import com.xbongbong.pro.product.pojo.dto.PagingProductDTO;
import com.xbongbong.pro.product.pojo.dto.ProductStockWarningListDTO;
import com.xbongbong.pro.product.pojo.vo.PagingProductVO;
import com.xbongbong.pro.product.pojo.vo.ProductStockWarningListVO;
import com.xbongbong.pro.product.pojo.vo.RelativeProductExplainVO;
import com.xbongbong.pro.service.toolbox.statistic.help.ChartDtoHelp;
import com.xbongbong.pro.service.toolbox.statistic.help.FiscalYearHelp;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.pro.statistic.pojo.FiscalYearTimePojo;
import com.xbongbong.pro.statistic.pojo.IndexThroughPojo;
import com.xbongbong.pro.statistic.result.pojo.dto.ChartResultBaseDTO;
import com.xbongbong.pro.statistic.through.pojo.dto.ResultThroughDTO;
import com.xbongbong.pro.statistic.through.pojo.vo.IndexThroughDTO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.pro.webexport.dto.CommunicatePlanExportDTO;
import com.xbongbong.pro.weblist.pojo.CustomerCommunicatePojo;
import com.xbongbong.pro.weblist.pojo.NearCustomerPojo;
import com.xbongbong.pro.weblist.pojo.TagPojo;
import com.xbongbong.pro.weblist.pojo.WaitOutstockProductPojo;
import com.xbongbong.pro.weblist.pojo.WaitPurchaseDetailPojo;
import com.xbongbong.pro.weblist.pojo.WaitPurchasePojo;
import com.xbongbong.pro.weblist.pojo.WaitPurchaseProductPojo;
import com.xbongbong.pro.weblist.pojo.dto.CommunicatePlanDTO;
import com.xbongbong.pro.weblist.pojo.dto.NearCustomerDTO;
import com.xbongbong.pro.weblist.pojo.vo.CommunicateVO;
import com.xbongbong.pro.weblist.pojo.vo.IndexCommunivateVo;
import com.xbongbong.pro.weblist.pojo.vo.NearCustomerListVO;
import com.xbongbong.pro.weblist.pojo.vo.WaitPurchaseDetailVO;
import com.xbongbong.pro.weblist.pojo.vo.WaitPurchaseProductVO;
import com.xbongbong.pro.weblist.pojo.vo.WorkReportVO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderDataEsListVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.fund.PaymentTaskConstant;
import com.xbongbong.saas.domain.dao.CustomerUserDao;
import com.xbongbong.saas.domain.entity.BatchFlowBillEntity;
import com.xbongbong.saas.domain.entity.CommunicatePlanUserEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.ContractUserEntity;
import com.xbongbong.saas.domain.entity.CouponTempleteEntity;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.DistributorAccountEntity;
import com.xbongbong.saas.domain.entity.DistributorAreaEntity;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.domain.entity.ProductSerialBalanceEntity;
import com.xbongbong.saas.domain.entity.ProductUnitPriceEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.PromotionActivityEntity;
import com.xbongbong.saas.domain.entity.PromotionProductEntity;
import com.xbongbong.saas.domain.entity.PurchaseBalanceEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.SmartReplenishmentEntity;
import com.xbongbong.saas.domain.entity.SpecificationEntity;
import com.xbongbong.saas.domain.entity.StockFlowBillEntity;
import com.xbongbong.saas.domain.entity.StockFlowBillEntityExt;
import com.xbongbong.saas.domain.entity.StockSurplusRecordEntity;
import com.xbongbong.saas.domain.entity.SupplierProductEntity;
import com.xbongbong.saas.domain.entity.TagLinkEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WriteOffRecordEntity;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.OutstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderEntityExt;
import com.xbongbong.saas.enums.BusinessCommentEnum;
import com.xbongbong.saas.enums.ChildProductFieldEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CreditTemporaryApplyStatusEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticDistributorEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticEnum;
import com.xbongbong.saas.enums.DistributorAddressEnum;
import com.xbongbong.saas.enums.GuaranteeExplainConstant;
import com.xbongbong.saas.enums.GuaranteeStatusEnum;
import com.xbongbong.saas.enums.ListBusinessTypeEnum;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.ListOptionTabEnum;
import com.xbongbong.saas.enums.ListTopButtonEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OptionTableHeadEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.ParentProductFieldEnum;
import com.xbongbong.saas.enums.PlaceholderEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.ReturnedPurchaseStatusEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SaasSubButtonEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.StockFilterTypeEnum;
import com.xbongbong.saas.enums.StockTypeEnum;
import com.xbongbong.saas.enums.SubOptionTableHeadEnum;
import com.xbongbong.saas.enums.TagEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.WarningSearchEnum;
import com.xbongbong.saas.enums.WriteOffRecordEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BatchFlowBillEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CostAdjustEnum;
import com.xbongbong.saas.enums.business.CreditTemporaryLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.business.FlowSubFormEnum;
import com.xbongbong.saas.enums.business.FundTransferEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.MarketingActivityManagementEnum;
import com.xbongbong.saas.enums.business.MarketingBaseEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.PaymentTaskEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductSerialBalanceEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PromotionActivityManagementEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SerialStatusEnum;
import com.xbongbong.saas.enums.business.SmartReplenishmentEnum;
import com.xbongbong.saas.enums.business.StockFlowBillEnum;
import com.xbongbong.saas.enums.business.StockStandingBookEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WaitInstockEnum;
import com.xbongbong.saas.enums.business.WaitOutstockEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.dictionary.ApplicableObjectTypeEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.enums.dictionary.ContractStatusEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.DistanceEnum;
import com.xbongbong.saas.enums.dictionary.MarketingStatusEnum;
import com.xbongbong.saas.enums.dictionary.OrderStatusEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.ProductionOrderStatusEnum;
import com.xbongbong.saas.enums.dictionary.PurchaseStatusEnum;
import com.xbongbong.saas.enums.product.ContractProductEnum;
import com.xbongbong.saas.enums.product.PriceProductEnum;
import com.xbongbong.saas.enums.product.PriceSetEnum;
import com.xbongbong.saas.enums.product.PromotionActivityManagementProductEnum;
import com.xbongbong.saas.enums.product.RefundProductEnum;
import com.xbongbong.saas.enums.subform.ProductStockSubFormEnum;
import com.xbongbong.saas.enums.subform.ProductWarehouseSubFormEnum;
import com.xbongbong.saas.feign.WorkOrderV2CommonFeignClient;
import com.xbongbong.saas.help.BaseHelp;
import com.xbongbong.saas.help.BasicHelper;
import com.xbongbong.saas.help.FieldAttrHelp;
import com.xbongbong.saas.help.MarketingHelp;
import com.xbongbong.saas.help.ProDetailHandlerHelp;
import com.xbongbong.saas.help.ProductListHelp;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.help.SaasAddHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.help.SearchFilterHelp;
import com.xbongbong.saas.model.BatchFlowBillModel;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.CouponTempleteModel;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.DistributorAccountModel;
import com.xbongbong.saas.model.DistributorAreaModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductSerialBalanceModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.PromotionActivityModel;
import com.xbongbong.saas.model.PromotionProductModel;
import com.xbongbong.saas.model.PurchaseBalanceModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.model.StockDateFilterModel;
import com.xbongbong.saas.model.StockFlowBillModel;
import com.xbongbong.saas.model.StockSurplusRecordModel;
import com.xbongbong.saas.model.SupplierProductModel;
import com.xbongbong.saas.model.TagLinkModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WriteOffRecordModel;
import com.xbongbong.saas.service.ClueService;
import com.xbongbong.saas.service.CommunicatePlanService;
import com.xbongbong.saas.service.ContactService;
import com.xbongbong.saas.service.ContractProductService;
import com.xbongbong.saas.service.ContractService;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.CustomerService;
import com.xbongbong.saas.service.FundTransferService;
import com.xbongbong.saas.service.InvoiceService;
import com.xbongbong.saas.service.KnowledgeDataService;
import com.xbongbong.saas.service.LikeService;
import com.xbongbong.saas.service.MarketActivityService;
import com.xbongbong.saas.service.OnlinePaymentFlowService;
import com.xbongbong.saas.service.OpportunityService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.PaymentService;
import com.xbongbong.saas.service.PaymentSheetService;
import com.xbongbong.saas.service.PaymentTaskService;
import com.xbongbong.saas.service.ProductCategoryService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.PurchaseInvoiceService;
import com.xbongbong.saas.service.PurchaseProductService;
import com.xbongbong.saas.service.QuotationService;
import com.xbongbong.saas.service.RefundService;
import com.xbongbong.saas.service.SaasListService;
import com.xbongbong.saas.service.SupplierCommunicateService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WarehouseService;
import com.xbongbong.saas.service.WorkOrderFormDataService;
import com.xbongbong.saas.service.WorkOrderService;
import com.xbongbong.saas.service.toolbox.handle.WebCommonDataValueMatchHandle;
import com.xbongbong.saas.service.toolbox.handle.WebListDataValueMatchHandle;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.ProductHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.ConditionEntity;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.PriceProductSetEntity;
import com.xbongbong.sys.domain.entity.PriceSetEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.enums.UserConfigEnum;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.PriceProductSetModel;
import com.xbongbong.sys.model.PriceSetModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/1/31 10:23
 * @since v1.0
 */
@Service("saasListService")
public class SaasListServiceImpl implements SaasListService {

    private static final Logger LOG = LoggerFactory.getLogger(SaasListServiceImpl.class);
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private UserConfigService userConfigService;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private UserModel userModel;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ProductService productService;
    @Resource
    private SearchFilterHelp searchFilterHelp;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private CustomerService customerService;
    @Resource
    private ContractService contractService;
    @Resource
    private OpportunityService opportunityService;
    @Resource
    private InvoiceService invoiceService;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private CallCenterCommonService callCenterCommonService;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    @Lazy
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private SupplierCommunicateService supplierCommunicateService;
    @Resource
    private EsHelper esHelper;
    @Resource
    private ProductCategoryService productCategoryService;
    @Resource
    private TagLinkModel tagLinkModel;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private ChartModel chartModel;
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private RefundService refundService;
    @Resource
    private ContactService contactService;
    @Resource
    private UserService userService;
    @Resource
    private PaymentService paymentService;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private ChartDtoHelp chartDtoHelp;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private CommunicatePlanService communicatePlanService;
    @Resource
    private PaasListGroupService paasListGroupService;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private ProductListHelp productListHelp;
    @Resource
    private WorkOrderFormDataService workOrderFormDataService;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private QuotationService quotationService;
    @Resource
    private SupplierProductModel supplierProductModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private WebDataAnalysisFactory webDataAnalysisFactory;
    @Resource
    private SaasAddHelp saasAddHelp;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private PurchaseInvoiceService purchaseInvoiceService;
    @Resource
    private CoUserService coUserService;
    @Resource
    private StockFlowBillModel stockFlowBillModel;
    @Resource
    private FormDataListSearchHelp formDataListSearchHelp;
    @Resource
    private StockDateFilterModel stockDateFilterModel;
    @Resource
    private PaymentSheetService paymentSheetService;
    @Resource
    private PayPlanSheetService payPlanSheetService;
    @Resource
    private StockSurplusRecordModel stockSurplusRecordModel;
    @Resource
    private FieldAttrHelp fieldAttrHelp;
    @Resource
    private PaymentTaskService paymentTaskService;
    @Resource
    private ProductSerialBalanceModel productSerialBalanceModel;
    @Resource
    private BatchFlowBillModel batchFlowBillModel;
    @Resource
    private OptionFactory optionFactory;
    @Resource
    private ProductAnalysisDataHandle productAnalysisDataHandle;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private BaseHelp baseHelp;
    @Resource
    private MarketActivityService marketActivityService;
    @Resource
    private ClueService clueService;
    @Resource
    private DistributorAccountModel distributorAccountModel;
    @Resource
    private CouponTempleteModel couponTempleteModel;
    @Resource
    private MarketingHelp marketingHelp;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private DistributorAreaModel distributorAreaModel;
    @Resource
    private PaasCommentService paasCommentService;
    @Resource
    private LikeService likeService;
    @Resource
    private ProductHelp productHelp;
    @Resource
    private PriceSetModel priceSetModel;
    @Resource
    private PriceProductSetModel priceProductSetModel;
    @Resource
    private PromotionActivityModel promotionActivityModel;
    @Resource
    private PromotionProductModel promotionProductModel;
    @Resource
    private OnlinePaymentFlowService onlinePaymentFlowService;
    @Resource
    private WriteOffRecordModel writeOffRecordModel;
    @Resource
    private WebCommonDataValueMatchHandle webCommonDataValueMatchHandle;
    @Resource
    private WebListDataValueMatchHandle webListDataValueMatchHandle;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private FundTransferService fundTransferService;
    @Resource
    private CustomerUserDao customerUserDao;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private PurchaseProductService purchaseProductService;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private PurchaseBalanceModel purchaseBalanceModel;
    @Resource
    private SpecificationModel specificationModel;
    @Resource
    private ContractProductService contractProductService;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private UserHelp userHelp;
    @Resource
    private ContractUserModel contractUserModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private ProDetailHandlerHelp proDetailHandlerHelp;
    @Resource
    private CommonListQry commonListQry;
    @Resource
    private PublicPoolListQry publicPoolListQry;

    @Resource
    private KnowledgeDataService knowledgeDataService;
    @Resource
    private ContractModel contractModel;

    @Resource
    private WorkOrderV2CommonFeignClient workOrderV2CommonFeignClient;

    @Override
    public PaasFormDataEsListVO customerList(FormDataListDTO formDataListDTO) throws XbbException {
        return commonListQry.execute(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO clueList(FormDataListDTO formDataListDTO) throws XbbException {
        return commonListQry.execute(formDataListDTO);
//        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
//        //评分区间筛选
//        saasListHelp.handleScoreRangeCondition(formDataListDTO.getCorpid(), formDataListDTO.getFormId(),formDataListDTO.getBusinessType(),conditionList);
//        handleConditionBySubBusinessType(formDataListDTO, conditionList);
//        UserEntity userEntity = new UserEntity();
//        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.CLUE.getCode(), formDataListDTO.getSubBusinessType());
//        // app端范围筛选
//        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.CLUE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
//        formDataListDTO.setConditions(conditionList);
//        formDataListDTO.setBusinessType(XbbRefTypeEnum.CLUE.getCode());
//        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO distributorList(FormDataListDTO formDataListDTO) throws XbbException {
        formDataListDTO.setBusinessType(XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode());
        formDataListDTO.setSubBusinessType(XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode());
        AbstractWebDataAnalysisHandle abstractWebDataAnalysisHandle = webDataAnalysisFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        if (Objects.isNull(abstractWebDataAnalysisHandle)) {
            return null;
        }
        PaasFormDataEsListVO paasFormDataEsListVO = abstractWebDataAnalysisHandle.analysisData(formDataListDTO);
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (notExport){
            paasFormDataEsListVO.setExplainMap(new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO distributorContactList(FormDataListDTO formDataListDTO) throws XbbException {
        formDataListDTO.setBusinessType(XbbRefTypeEnum.DISTRIBUTOR_CONTACT.getCode());
        formDataListDTO.setSubBusinessType(XbbRefTypeEnum.DISTRIBUTOR_CONTACT.getCode());
        AbstractWebDataAnalysisHandle abstractWebDataAnalysisHandle = webDataAnalysisFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        if (Objects.isNull(abstractWebDataAnalysisHandle)) {
            return null;
        }
        PaasFormDataEsListVO paasFormDataEsListVO = abstractWebDataAnalysisHandle.analysisData(formDataListDTO);
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (notExport){
            paasFormDataEsListVO.setExplainMap(new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
        }
        return paasFormDataEsListVO;
    }

    @Override
    public CommunicateVO distributorCommunicateList(FormDataListDTO formDataListDTO) throws XbbException {
        formDataListDTO.setBusinessType(XbbRefTypeEnum.DISTRIBUTOR_COMMUNICATE.getCode());
        formDataListDTO.setSubBusinessType(XbbRefTypeEnum.DISTRIBUTOR_COMMUNICATE.getCode());
        AbstractWebDataAnalysisHandle abstractWebDataAnalysisHandle = webDataAnalysisFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        PaasFormDataEsListVO paasFormDataEsListVO = abstractWebDataAnalysisHandle.analysisData(formDataListDTO);
        // web端逻辑，主要处理下关于关联数据，用户，部门数据回显的问题 end
        List<CustomerCommunicatePojo> customerCommunicatePojoList = new ArrayList<>();
        List<Long> dataIdIn = new ArrayList<>();
        List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();
        if(paasFormDataESList != null && !paasFormDataESList.isEmpty()){
            for (PaasFormDataEntityExt entity : paasFormDataESList) {
                dataIdIn.add(entity.getDataId());
            }
            dataIdIn.add(-1L);
            Map<Long,Integer> commnetCountMap = paasCommentService.getCommnetCountMap(dataIdIn,formDataListDTO.getCorpid(), BusinessCommentEnum.DISTRIBUTOR_COMMUNICATE.getCode());
            Map<Long,Integer> likeCountMap = likeService.getLikeCountMap(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.DISTRIBUTOR_COMMUNICATE.getCode());
            List<Long> hasCommentIdList = paasCommentService.hasMyComment(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.DISTRIBUTOR_COMMUNICATE.getCode(),formDataListDTO.getUserId());
            List<Long> hasLikeIdList = likeService.hasMyLike(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.DISTRIBUTOR_COMMUNICATE.getCode(),formDataListDTO.getUserId());
            for (PaasFormDataEntityExt entity : paasFormDataESList) {
                JSONObject data = entity.getData();
                JSONArray distributorArr = data.getJSONArray(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
                Long customerId = null;
                if (CollectionsUtil.isNotEmpty(distributorArr)) {
                    customerId = distributorArr.getJSONObject(0).getLong(BusinessConstant.ID);
                }
                String customerName = data.getString(CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
                String creatorId = data.getString(CustomerCommunicateEnum.USER_ID.getAttr());
                String userName = data.getString(CustomerCommunicateEnum.USER_NAME.getAttr());
                Object userAvatar = data.get(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                try {
                    CustomerCommunicatePojo customerCommunicatePojo = commonHelp.setCommunicatePojo(commnetCountMap, likeCountMap, hasCommentIdList, hasLikeIdList, entity, data, customerId, customerName, creatorId, userName, userAvatar, paasFormDataEsListVO.getExplainMap(), true, DistributorMarkEnum.DISTRIBUTOR.getCode());
                    customerCommunicatePojoList.add(customerCommunicatePojo);
                } catch (Exception e) {
                    LOG.error("经销商跟进保存错误", e);
                }
            }
        }
        CommunicateVO communicateVO = new CommunicateVO();
        communicateVO.setResultMap(customerCommunicatePojoList);
        communicateVO.setPageHelper(paasFormDataEsListVO.getPageHelper());
        communicateVO.setTopPermissions(paasFormDataEsListVO.getTopPermissions());
        return communicateVO;
    }

    @Override
    public PaasFormDataEsListVO reimbursementFormList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer businessType = formDataListDTO.getBusinessType();
        if (!Objects.equals(businessType,XbbRefTypeEnum.REIMBURSEMENT_FORM.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        formDataListDTO.setBusinessType(XbbRefTypeEnum.REIMBURSEMENT_FORM.getCode());
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.REIMBURSEMENT_FORM.getCode(), formDataListDTO.getSubBusinessType());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO expenseList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer businessType = formDataListDTO.getBusinessType();
        if (!Objects.equals(businessType,XbbRefTypeEnum.EXPENSE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        formDataListDTO.setBusinessType(XbbRefTypeEnum.EXPENSE.getCode());
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.EXPENSE.getCode(), formDataListDTO.getSubBusinessType());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public ProductStockWarningListVO productStockWarningList(ProductStockWarningListDTO productStockWarningListDTO) throws XbbException {
        ProductStockWarningListVO productStockWarningListVO = new ProductStockWarningListVO();
        try {
            String corpid = productStockWarningListDTO.getCorpid();
            // 拼装列表数据查询DTO
            FormDataListDTO formDataListDTO = new FormDataListDTO();
            BeanUtil.copyProperties(productStockWarningListDTO, formDataListDTO);
            formDataListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
            formDataListDTO.setSubBusinessType(XbbRefTypeEnum.STOCK_SEARCH.getCode());
            formDataListDTO.setDefaultGroup(1);
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
            if (Objects.isNull(paasFormEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            formDataListDTO.setAppId(paasFormEntityExt.getAppId());
            formDataListDTO.setFormId(paasFormEntityExt.getId());
            formDataListDTO.setSaasMark(1);
            formDataListDTO.setListGroupId(ListGroupEnum.WARNING_SEARCH.getCode().longValue());
            formDataListDTO.setPlatform(StringConstant.PLATFORM_WEB);
            // 首页没有conditions
            List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
            if(conditionList == null) {
                conditionList = new ArrayList<>();
            }
            formDataListDTO.setConditions(conditionList);
            PaasFormDataEsListVO paasFormDataEsListVO = newProductStockList(formDataListDTO);

            // 返回格式处理
            PageHelper pageHelper = paasFormDataEsListVO.getPageHelper();
            // 总条数
            Integer rowsCount = pageHelper.getRowsCount();

            // 表头
            JSONArray tableHeadArray = new JSONArray();
            // saasAttr为null或者解释中不包含的，为必须显示的
            List<SubOptionTableHeadEnum> subOptionTableHeadEnums = Arrays.asList(SubOptionTableHeadEnum.PRODUCT_SPEC_NO, SubOptionTableHeadEnum.WARNING_WAREHOUSE_UPPER, SubOptionTableHeadEnum.WARNING_WAREHOUSE_LOWER);
            subOptionTableHeadEnums.forEach((item) -> {
                JSONObject tablHeadObj = new JSONObject();
                tablHeadObj.put(StringConstant.PROP, item.getProp());
                tablHeadObj.put(StringConstant.LABEL, item.getLabel());
                tableHeadArray.add(tablHeadObj);
            });

            List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();
            JSONArray resultArray = new JSONArray();
            for (PaasFormDataEntityExt product : paasFormDataESList) {
                JSONObject productObj = new JSONObject();
                Long productId = product.getDataId();
                JSONObject dataList = product.getData();
                String productName = dataList.getString(ProductEnum.NAME.getAttr());
                String productNo = dataList.getString(ProductEnum.PRODUCT_NO.getAttr());


                // 拼装数据
                productObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, productId);
                productObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, productName);
                productObj.put(SubOptionTableHeadEnum.PRODUCT_SPEC_NO.getProp(), productNo);
                JSONObject optionObj = dataList.getJSONObject(ListOptionEnum.OVER_LIMIT_NUM.getAttr());
                if (Objects.equals(optionObj.getInteger("overLimitType"),1)){
                    productObj.put(SubOptionTableHeadEnum.WARNING_WAREHOUSE_UPPER.getProp(), optionObj.getString("overNum"));
                }else if (Objects.equals(optionObj.getInteger("overLimitType"),2)){
                    productObj.put(SubOptionTableHeadEnum.WARNING_WAREHOUSE_LOWER.getProp(), optionObj.getString("overNum"));

                }

                resultArray.add(productObj);
            }

            productStockWarningListVO.setTableHead(tableHeadArray);
            productStockWarningListVO.setValue(resultArray);
            productStockWarningListVO.setRowsCount(rowsCount);
            // 获取库存预警的分组
            ListGroupListDTO listGroupListDTO = new ListGroupListDTO();
            BeanUtil.copyProperties(formDataListDTO, listGroupListDTO);
            listGroupListDTO.setSubBusinessType(XbbRefTypeEnum.STOCK_SEARCH.getCode());
            GroupListVO groupListVO = paasListGroupService.list(listGroupListDTO);
            if (Objects.nonNull(groupListVO) && Objects.nonNull(groupListVO.getListGroupList()) && !groupListVO.getListGroupList().isEmpty()) {
                groupListVO.getListGroupList().stream().filter(item -> Objects.equals(XbbRefTypeEnum.WARNING_SEARCH.getAlias(), item.getDefaultAlias())).forEach(item -> {
                    ListGroupVO listGroupVO = new ListGroupVO();
                    BeanUtil.copyProperties(item, listGroupVO);
                    listGroupVO.setListGroupId(item.getId());
                    productStockWarningListVO.setListGroup(listGroupVO);
                });
            }
        } catch (Exception e) {
            LOG.error("saasListSerivce.productStockWarningList 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return productStockWarningListVO;
    }


    @Override
    public PaasFormDataEsListVO  newProductStockList(FormDataListDTO formDataListDTO) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        // 分类
        Long categoryId = 0L;
        // 仓库
        List<Long> selectWarehouseIdList = new ArrayList<>();
        formDataListDTO.setSelectWarehouseIdList(selectWarehouseIdList);
        // 预计类型
        Integer warningType = 0;
        // 保质状态
        Integer guaranteeStatus = 0;
        if (formDataListDTO.getCommonFilter() != null && !formDataListDTO.getCommonFilter().isEmpty()) {
            warningType = formDataListDTO.getCommonFilter().getInteger("warningType");
            warningType = warningType == null ? 0 : warningType;
            guaranteeStatus = formDataListDTO.getCommonFilter().getInteger("guaranteeStatus");
            guaranteeStatus = guaranteeStatus == null ? 0 : guaranteeStatus;

        }
        // 分组
        //Integer listGroupId = Objects.isNull(formDataListDTO.getListGroupId()) ? ListGroupEnum.PRODUCT_SEARCH.getCode() : formDataListDTO.getListGroupId().intValue();
        // 改成多模板后用formId来替换原先的分组以区分业务
        ListGroupEnum listGroupEnum = ListGroupEnum.getByCode(formDataListDTO.getFormId().intValue());
        // 筛选条件集合
        List<Long> warehouseIdList = selectWarehouseIdList;
        List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
        List<ConditionsEntityExt> productSearchConditions = new ArrayList<>();
        List<List<ConditionsEntityExt>> shouldConditions = formDataListDTO.getShouldConditions();
        Iterator<ConditionsEntityExt> iterator = conditionsEntityExtList.iterator();
        boolean hasWarehouseFilter = false;
        List<Long> supplierIdList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConditionsEntityExt conditionsEntity = iterator.next();
            if (Objects.equals(ProductEnum.WAREHOUSE.getAttr(), conditionsEntity.getAttr())) {
                List<Object> selectValues = conditionsEntity.getValue();
                selectValues.forEach(item -> selectWarehouseIdList.add(Long.valueOf(item.toString())));
                hasWarehouseFilter = true;
            } else if (Objects.equals(ProductEnum.CATEGORY_ID.getAttr(), conditionsEntity.getAttr())) {
                List<Object> selectValues = conditionsEntity.getValue();
                // 24989 【app-库存查询】分类为空时，列表筛选分类，提示：网络请求失败
                selectValues.removeAll(Collections.singleton(null));
                for (Object selectValue : selectValues) {
                    categoryId = Long.valueOf(selectValue.toString());
                }
                iterator.remove();
            } else if (Objects.equals(conditionsEntity.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                conditionsEntity.setAttr(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
            } else if (Objects.equals(conditionsEntity.getAttr(),ProductEnum.SUPPLIER.getAttr())) {
                List<Object> selectValues = conditionsEntity.getValue();
                selectValues.forEach(item -> supplierIdList.add(Long.valueOf(item.toString())));
                iterator.remove();
            }
        }
        // 供应商筛选
        if (!supplierIdList.isEmpty()) {
            List<SupplierProductEntity> supplierProductEntities = supplierProductModel.getSupplierProductBySupplierIdIn(corpid, supplierIdList);
            Set<Long> productIdIn = new HashSet<>();
            supplierProductEntities.forEach(item -> productIdIn.add(item.getProductId()));
            conditionsEntityExtList.add(new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(),"",FieldTypeEnum.DATAID.getType(),ConditionEnum.IN.getSymbol(),new ArrayList<>(productIdIn)));
        }
        // 仓库权限 + 筛选
        List<Long> allWarehouseIdList = warehouseService.getWarehouseIdsByPermission(formDataListDTO.getLoginUser(),formDataListDTO.getLoginUser().getDepSet());
        if (!hasWarehouseFilter) {
            if (!formDataListDTO.getLoginUser().isMaxDataPermission()){
                warehouseIdList = allWarehouseIdList;
                // 低权限展开的仓库限定
                formDataListDTO.setSelectWarehouseIdList(warehouseIdList);
                if (Objects.equals(listGroupEnum,ListGroupEnum.WARNING_SEARCH)) {
                    allWarehouseIdList.add(0L);
                } else if (warehouseIdList.isEmpty()) {
                    allWarehouseIdList.add(-1L);
                }
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.WAREHOUSE.getAttr(),"",ProductEnum.WAREHOUSE.getFieldType(),ConditionEnum.INCLUDE.getSymbol(),new ArrayList<>(warehouseIdList)));
            } else {
//                if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
//                    conditionsEntityExtList.add(new ConditionsEntityExt("warehouseId", "", ProductEnum.WAREHOUSE.getFieldType(), ConditionEnum.NOEMPTY.getSymbol(), new ArrayList<>()));
//                }
            }
        } else {
            allWarehouseIdList.retainAll(warehouseIdList);
        }
        // 分类筛选
        if (categoryId > 0) {
            List<Long> categoryIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<ProductCategoryEntity> productCategoryList = productCategoryService.getSubCategoryIdList(corpid, categoryId);
            productCategoryList.forEach((item)-> categoryIdIn.add(item.getId()));
            if (!categoryIdIn.isEmpty()) {
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.CATEGORY_ID.getAttr(),"",ProductEnum.CATEGORY_ID.getFieldType(),ConditionEnum.IN.getSymbol(),new ArrayList<>(categoryIdIn)));
            }
        }
        // 公司配置：是否显示0库存
        CompanyConfigHasBeenEnableDTO companyConfigHasBeenEnableDTO = new CompanyConfigHasBeenEnableDTO(CompanyConfigEnum.ZERO_STOCK.getAlias());
        BeanUtil.copyProperties(formDataListDTO,companyConfigHasBeenEnableDTO);
        CompanyConfigHasBeenEnableVO companyConfigHasBeenEnableVO = companyConfigService.hasBeenEnable(companyConfigHasBeenEnableDTO);
        if (Objects.equals(companyConfigHasBeenEnableVO.getEnable(),1)) {
            conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.STOCK.getAttr(), "", ProductEnum.STOCK.getFieldType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(0)));
            productSearchConditions.add(new ConditionsEntityExt(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.NUM), "", FieldTypeEnum.NUM.getType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(0)));
        }
        // 当前登陆人信息
        saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditions,formDataListDTO.getLoginUser(),XbbRefTypeEnum.PRODUCT.getCode(),formDataListDTO.getLoginUser().getDepSet());
        PaasFormEntityExt paasFormEntityExt;
        switch (listGroupEnum){
            case WARNING_SEARCH:
                paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                FieldTypeEnum warnTypeEnum = WarningSearchEnum.getWarnTypeEnum(warningType);
                productSearchConditions.add(new ConditionsEntityExt(warnTypeEnum.getAlias(),"",warnTypeEnum.getType(),ConditionEnum.EQUAL.getSymbol(),Collections.singletonList(1)));
                formDataListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.WARNING_SEARCH.getCode());
                formDataListDTO.setFormId(paasFormEntityExt.getId());
                break;
            case GUARANTEE_SEARCH:
                //保质期查询
                if (!warehouseIdList.isEmpty()) {
                    productSearchConditions.add(new ConditionsEntityExt(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.WAREHOUSE_ID),"",FieldTypeEnum.BATCH_WAREHOUSE_ID.getType(),ConditionEnum.IN.getSymbol(),new ArrayList<>(warehouseIdList)));
                }
                paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                GuaranteeStatusEnum guaranteeStatusEnum;
                // 兼容前端第一次进来拿不到分组id
                Integer groupId = Objects.nonNull(formDataListDTO.getListGroupId()) ? formDataListDTO.getListGroupId().intValue() : -1;
                if (Objects.equals(groupId, ListGroupEnum.GUARANTEE_SEARCH_EXPIRED.getCode())) {
                    guaranteeStatusEnum = GuaranteeStatusEnum.OUT_OF_DATE;
                    productSearchConditions.add(new ConditionsEntityExt(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.EXPIRE_DATE), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.RANGE.getSymbol(), Arrays.asList(guaranteeStatusEnum.getTime(), DateTimeUtil.getInt() + guaranteeStatusEnum.getTime())));
                } else if (Objects.equals(groupId, ListGroupEnum.GUARANTEE_SEARCH_EXPIRED_15.getCode())) {
                    guaranteeStatusEnum = GuaranteeStatusEnum.EXPIRE_IN_FIFTEEN;
                    productSearchConditions.add(new ConditionsEntityExt(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.EXPIRE_DATE), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.RANGE.getSymbol(), Arrays.asList(DateTimeUtil.getInt(), guaranteeStatusEnum.getTime() + DateTimeUtil.getInt())));
                } else if (Objects.equals(groupId, ListGroupEnum.GUARANTEE_SEARCH_EXPIRED_30.getCode())) {
                    guaranteeStatusEnum = GuaranteeStatusEnum.EXPIRE_IN_THIRTY;
                    productSearchConditions.add(new ConditionsEntityExt(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.EXPIRE_DATE), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.RANGE.getSymbol(), Arrays.asList(DateTimeUtil.getInt(), guaranteeStatusEnum.getTime() + DateTimeUtil.getInt())));
                } else if (Objects.equals(groupId, ListGroupEnum.GUARANTEE_SEARCH_EXPIRED_60.getCode())) {
                    guaranteeStatusEnum = GuaranteeStatusEnum.EXPIRE_OVER_SIXTY;
                    productSearchConditions.add(new ConditionsEntityExt(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.EXPIRE_DATE), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.RANGE.getSymbol(), Arrays.asList(DateTimeUtil.getInt(), guaranteeStatusEnum.getTime() + DateTimeUtil.getInt())));
                } else if (Objects.equals(groupId, ListGroupEnum.GUARANTEE_SEARCH_EXPIRED_60_MORE.getCode())) {
                    guaranteeStatusEnum = GuaranteeStatusEnum.EXPIRE_OVER_SIXTY;
                    productSearchConditions.add(new ConditionsEntityExt(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.EXPIRE_DATE), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.GREATERTHAN.getSymbol(), Collections.singletonList(guaranteeStatusEnum.getTime())));
                }
                formDataListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.GUARANTEE_SEARCH.getCode());
                formDataListDTO.setFormId(paasFormEntityExt.getId());
                break;
            default:
                if (!warehouseIdList.isEmpty()) {
                    productSearchConditions.add(new ConditionsEntityExt(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_ID),"",FieldTypeEnum.BATCH_WAREHOUSE_ID.getType(),ConditionEnum.IN.getSymbol(),new ArrayList<>(warehouseIdList)));
                }
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.PARENT_ID.getAttr(),"",ProductEnum.PARENT_ID.getFieldType(),ConditionEnum.NOEQUAL.getSymbol(),Collections.singletonList(0)));
                break;
        }
        formDataListDTO.setProductSerchConditions(productSearchConditions);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);

        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        if (Objects.isNull(paasFormExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> headList = paasFormDataEsListVO.getHeadList();
        List<String> stockAttrList = Arrays.asList("currentStock", "minimumStock", "maximumStock");
        FieldAttrEntity stockField = null;
        FieldAttrEntity enableMultiUnitField = null;
        for (FieldAttrEntity fieldAttrEntity : headList) {
            if (Objects.equals(SelectProductEnum.STOCK.getSaasAttr(), fieldAttrEntity.getAttr()) || Objects.equals(ProductEnum.STOCK.getAttr(), fieldAttrEntity.getAttr()) || stockAttrList.contains(fieldAttrEntity.getAttr())) {
                stockField = fieldAttrEntity;
            } else if (Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.ENABLE_MULTI_UNIT.getAttr())) {
                enableMultiUnitField = fieldAttrEntity;
            }
        }
        // 预警查询和保质期查询展示的子产品。但是点击产品跳转详情时需要传父产品id
        List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();
        //获取产品Id集合
        Map<Long, ContractProductEntity> contractProductEntityMap = new HashMap<>();
        if (!paasFormDataESList.isEmpty()) {
            List<Long> productIdList = new ArrayList<>();
            for (PaasFormDataEntityExt entity : paasFormDataESList) {
                productIdList.add(entity.getId());
            }
            //获取产品的待出库数量
            List<ContractProductEntity> waitOutProductEntitys = contractProductService.getWaitOutstockProductByProductIdIn(productIdList, corpid);
            if (CollectionsUtil.isNotEmpty(waitOutProductEntitys)) {
                for (ContractProductEntity contractProductEntity : waitOutProductEntitys) {
                    contractProductEntityMap.put(contractProductEntity.getProductId(), contractProductEntity);
                }
            }
        }
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
            JSONObject productData = paasFormDataEntityExt.getData();
            Long productId=paasFormDataEntityExt.getId();
            if (productData == null) {
                continue;
            }
            Long parentId = StringUtil.StringToLong(productData.getString(ProductEnum.PARENT_ID.getAttr()), 0L);
            paasFormDataEntityExt.setParentId(parentId);

            // 字段穿透
            if (notExport) {
                if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                    JSONObject nameObject = new JSONObject();
                    nameObject.put("name", productData.getString(ProductEnum.NAME.getAttr()));
                    nameObject.put("id", paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                    nameObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
                    nameObject.put("businessType", XbbRefTypeEnum.PRODUCT.getCode());
                    productData.put(ProductEnum.NAME.getAttr(), Collections.singleton(nameObject));

                    JSONObject serialObject = new JSONObject();
                    serialObject.put("name", productData.getString(ProductEnum.SERIALNO.getAttr()));
                    serialObject.put("id", paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                    serialObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
                    serialObject.put("businessType", XbbRefTypeEnum.PRODUCT.getCode());
                    productData.put(ProductEnum.SERIALNO.getAttr(), Collections.singleton(serialObject));
                }
            }
            if (notExport) {
                if (Objects.equals(productData.get(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr()), BasicConstant.ONE)) {
                    productData.put(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr(), OperateTypeEnum.YES.getName());
                }else {
                    productData.put(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr(), OperateTypeEnum.NO.getName());
                }
                if (Objects.equals(productData.get(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()), BasicConstant.ONE)) {
                    productData.put(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr(), OperateTypeEnum.YES.getName());
                }else {
                    productData.put(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr(), OperateTypeEnum.NO.getName());
                }
            }

            if (Objects.nonNull(enableMultiUnitField)) {
                int enableMultiUnit = productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr());
                productData.put(enableMultiUnitField.getAttr(), Objects.equals(enableMultiUnit, 1) ? OperateTypeEnum.YES.getName() : OperateTypeEnum.NO.getName());
            }
            //设置可用库存量值
            if (!contractProductEntityMap.isEmpty() && Objects.nonNull(contractProductEntityMap.get(productId))) {
                if (Objects.nonNull(productData.get(ProductEnum.STOCK.getAttr()))) {
                    if (productData.get(ProductEnum.STOCK.getAttr()) instanceof Number) {
                        productData.put("availableStock", Arith.sub(productData.getDouble(ProductEnum.STOCK.getAttr()), contractProductEntityMap.get(productId).getSumNum()));
                    }
                } else {
                    productData.put("availableStock", "");
                }
            }else {
                //如果没有待出库数量，可用库存量=库存
                productData.put("availableStock",productData.get(ProductEnum.STOCK.getAttr()));
            }
        }
        if (notExport) {
            for (FieldAttrEntity fieldAttrEntity : headList) {
                if (Objects.equals(ProductEnum.NAME.getAttr(), fieldAttrEntity.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.SERIALNO.getAttr())) {
                    fieldAttrEntity.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }
            }
        }

        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO contactList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer businessType = formDataListDTO.getBusinessType();
        if (!Objects.equals(businessType,XbbRefTypeEnum.CONTACT.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        formDataListDTO.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());

        return commonListQry.execute(formDataListDTO);

    }

    @Override
    public PaasFormDataEsListVO communicatePlanList(CommunicatePlanDTO communicatePlanDTO) throws XbbException {
        Integer businessType = communicatePlanDTO.getBusinessType();
        if (businessType == null &&  (null == (businessType = communicatePlanDTO.getSubBusinessType())) || !Objects.equals(businessType,XbbRefTypeEnum.COMMUNICATE_PLAN.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        if (null == communicatePlanDTO.getBusinessType()){
            communicatePlanDTO.setBusinessType(businessType);
        }
        List<ConditionsEntityExt> conditionsEntityExtList = communicatePlanService.setConditionList(communicatePlanDTO);
//        communicatePlanService.setDataCondition(communicatePlanDTO,conditionsEntityExtList);
        // 父子文档查询
        communicatePlanService.setTeamCondition(communicatePlanDTO, conditionsEntityExtList);
        //创建时间(区间)
        ConditionsEntityExt dateCondition = new ConditionsEntityExt();
        Integer dateInt;
        try {
            String date = communicatePlanDTO.getDate();
            dateInt = StringUtil.isEmpty(date) ? DateUtil.getTodayInt() : DateUtil.getInt(date,DateUtil.SDFDate);
        }catch (Exception e){
            throw new XbbException(CommuicatePlanErrorCodeEnum.API_ERROR_214006);
        }
        dateCondition.setAttr(CommunicatePlanEnum.COMMUNICATE_TIME.getAttr());
        dateCondition.setFieldType(CommunicatePlanEnum.COMMUNICATE_TIME.getFieldType());
        dateCondition.setName(CommunicatePlanEnum.COMMUNICATE_TIME.getAttrName());
        dateCondition.setSymbol(ConditionEnum.RANGE.getSymbol());
        dateCondition.setValue(Arrays.asList(dateInt,dateInt + TimeConstant.SECONDS_PER_DAY));
        conditionsEntityExtList.add(dateCondition);
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(communicatePlanDTO, formDataListDTO);
        formDataListDTO.setConditions(conditionsEntityExtList);
        // 访客计划列表按照执行时间升序
        Map<String, String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        sortMap.put("field", CommunicatePlanEnum.COMMUNICATE_TIME.getAttr());
        sortMap.put("sort", "asc");
        formDataListDTO.setSortMap(sortMap);
        return paasFormDataService.listByEs(formDataListDTO);
    }


    @Override
    public SearchFilterVO getSearchFilter(ListAppSearchFilterDTO listAppSearchFilterDTO) throws XbbException {
        Long formId = listAppSearchFilterDTO.getFormId();
        Integer businessType = listAppSearchFilterDTO.getBusinessType();
        Integer subBusinessType = listAppSearchFilterDTO.getSubBusinessType();
        XbbRefTypeEnum refTypeEnum;
        if (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())||
                Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_OUTSTOCK.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode())){
            refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        }else {
            refTypeEnum = XbbRefTypeEnum.getByCode(subBusinessType);
        }
        String corpid = listAppSearchFilterDTO.getCorpid();
        ListGroupEnum listGroupEnum = ListGroupEnum.getByCode(formId.intValue());
        Integer distributorMark = listAppSearchFilterDTO.getDistributorMark();

        List<FieldAttrEntity> explainList = new ArrayList<>();
        if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderExplainEntity workOrderExplainEntity;
            if (Objects.equals(formId, 0L)) {
                // 工单全部列表
                workOrderExplainEntity = workOrderExplainModel.getDefaultAllListExplain(corpid);
            } else {
                workOrderExplainEntity = workOrderExplainModel.getByFormId(formId, corpid);
            }
            if (Objects.isNull(workOrderExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.INSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.PURCHASE_INSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.REFUND_INSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.OTHER_INSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.OUTSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode())) {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(subBusinessType, corpid);
            if (paasFormExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        } else if(Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode())){
            //工作报告
            PaasFormExplainEntity paasFormExplainEntity;
            if (Objects.equals(formId, 0L) || Objects.isNull(formId)) {
                paasFormExplainEntity = paasFormExplainModel.getWorkReportDefaultAllListExplain();
                if (Objects.isNull(paasFormExplainEntity)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
            } else {
                Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                paramMap.put(ParameterConstant.FORMID,formId);
                paramMap.put(ParameterConstant.CORPID,corpid);
                paramMap.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
                //paramMap.put("businessType",businessType);
                List<PaasFormExplainEntity> list = paasFormExplainModel.list(paramMap);
                if (list == null || list.isEmpty()) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                paasFormExplainEntity = list.get(0);
            }
            explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
            explainList = productHelp.getProductPriceFieldList(corpid);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())) {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
            explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        } else {
            PaasFormExplainEntity paasFormExplainEntity;
            // 预警查询和批次保质期查询
            if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
                if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.WARNING_SEARCH.getCode()) || Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                    formId = paasFormEntityExt.getId();
                    listAppSearchFilterDTO.setFormId(formId);
                }
            }
            if (Objects.nonNull(formId) && !Objects.equals(formId, 0L)) {
                paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            } else {
                paasFormExplainEntity = paasFormExplainModel.getByBusinessType4Distributor(listAppSearchFilterDTO.getBusinessType(), corpid, distributorMark);
            }
            if (paasFormExplainEntity == null || Objects.equals(paasFormExplainEntity.getDel(), DelEnum.DELETE.getDel())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            //防止前端未传该参数（只有formId不为空时才正确）
            distributorMark = paasFormExplainEntity.getDistributorMark();
            explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        }
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())
                || Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_PURCHASE.getCode())
                || Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())) {
            saasListHelp.handelSaasSpecialList(explainList, businessType, subBusinessType);
        }
        if (Objects.equals(listAppSearchFilterDTO.getPlatform(),PlatFormEnum.DINGTALK.getValue())
                && Objects.equals(listAppSearchFilterDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())
                && Objects.equals(listAppSearchFilterDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            saasListHelp.handleWaitInstockExplain(explainList);
        }
        if (Objects.equals(listAppSearchFilterDTO.getPlatform(),PlatFormEnum.DINGTALK.getValue())
                && Objects.equals(listAppSearchFilterDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())
                && Objects.equals(listAppSearchFilterDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            saasListHelp.handleWaitOutstockExplain(explainList);
        }
        if (Objects.equals(listAppSearchFilterDTO.getPlatform(),PlatFormEnum.DINGTALK.getValue())
                && Objects.equals(listAppSearchFilterDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_PURCHASE.getCode())
                && Objects.equals(listAppSearchFilterDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            saasListHelp.handleWaitPurchaseExplain(explainList);
        }
        Map<String, FieldAttrEntity> explainMap = new LinkedHashMap<>(explainList.size());
        // 将字段放入字段容器
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
        }
        // 搜索框PlaceHolder
        Map<String, Object> searchMap = PlaceholderEnum.getAppListSearchPlaceHolder(refTypeEnum.getCode(), distributorMark);
        // 筛选
//        JSONArray filterArray = null;
        // 特殊筛选
        JSONArray specialFilterArray = null;
        // 排序
        JSONArray orderArray = null;
        //筛选
        List<Object> objs = new ArrayList<>();
        List<SelectOptionPojo> orderOptionPojoList = new ArrayList<>();
        // 是否有排序设置
        boolean isSortSet = false;

        UserVO userVO = listAppSearchFilterDTO.getLoginUser();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);

        JSONObject explains = new JSONObject();
        switch (refTypeEnum) {
            case CUSTOMER_MANAGEMENT:
            case CUSTOMER:
            case CUSTOMER_FOCUS:
            case CUSTOMER_DEAL:
            case CUSTOMER_FOLLOW:
//                filterArray = searchFilterHelp.getCustomerFilter(corpid,formId, explainMap);
                orderOptionPojoList = searchFilterHelp.getCustomerOrder(explainMap);
                isSortSet = true;
                break;
            case CUSTOMER_PUBLIC:
//                filterArray = searchFilterHelp.getPublicCustomerFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getCustomerOrder(explainMap);
                isSortSet = true;
                break;
            case CUSTOMER_NEARBY:
//                filterArray = searchFilterHelp.getCustomerFilter(corpid,formId, explainMap);
                specialFilterArray = searchFilterHelp.getCustomerSpecialFilter();
                break;
            case CUSTOMER_DUPLICATE:
                break;
            case CONTACT:
//                filterArray = searchFilterHelp.getContactFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getContactOrder(explainMap);
                isSortSet = true;
                break;
            case ALL_OPPORTUNITY:
            case KEY_OPPORTUNITY:
//                filterArray = searchFilterHelp.getOpportunityFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getOpportunityOrder(explainMap);
                isSortSet = true;
                break;
            case INVOICE:
//                filterArray = searchFilterHelp.getInvoiceFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getInvoiceOrder(explainMap);
                isSortSet = true;
                break;
            case PURCHASE_INVOICE:
//                filterArray = searchFilterHelp.getPurchaseInvoiceFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getPurchaseInvoiceOrder(explainMap);
                isSortSet = true;
                break;
            case WORK_REPORT:
//                filterArray = searchFilterHelp.getWorkReportFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getWorkReportOrder(explainMap);
                isSortSet = true;
                break;
            case CONTRACT:
//                filterArray = searchFilterHelp.getContractFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getContractOrder(explainMap);
                isSortSet = true;
                break;
            case QUOTATION:
//                filterArray = searchFilterHelp.getQuotationFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getQuotationOrder(explainMap);
                isSortSet = true;
                break;
            case PAYMENT:
//                filterArray = searchFilterHelp.getPaymentFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getPaymentOrder(explainMap);
                isSortSet = true;
                break;
            case CUSTOMER_COMMUNICATE:
//                filterArray = searchFilterHelp.getCommunicateFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getCommunicateOrder(explainMap);
                isSortSet = true;
                break;
            case SUPPLIER_COMMUNICATE:
//                filterArray = searchFilterHelp.getSupplierCommunicateFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getSupplierCommunicateOrder(explainMap);
                isSortSet = true;
                break;
            case SUPPLIER:
//                filterArray = searchFilterHelp.getSupplierFilter(corpid, formId, explainMap);
                orderOptionPojoList = searchFilterHelp.getSupplierOrder(explainMap);
                isSortSet = true;
                break;
            case SUPPLIER_CONTACT:
//                filterArray = searchFilterHelp.getSupplierContactFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getSupplierContactOrder(explainMap);
                isSortSet = true;
                break;
            case PURCHASE:
//                filterArray = searchFilterHelp.getPurchaseFilter(corpid, formId, explainMap);
                orderOptionPojoList = searchFilterHelp.getPurchaseOrder(explainMap);
                isSortSet = true;
                break;
            case RETURNED_PURCHASE:
//                filterArray = searchFilterHelp.getReturnedPurchaseFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getReturnedPurchaseOrder(explainMap);
                isSortSet = true;
                break;
            case BOM_BILL:
//                filterArray = searchFilterHelp.getBomBillFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getBomBillOrder(explainMap);
                isSortSet = true;
                break;
            case PRODUCTION_ORDER:
//                filterArray = searchFilterHelp.getProductionOrderFilter(listAppSearchFilterDTO, explainMap);
                orderOptionPojoList = searchFilterHelp.getProductionOrderOrder(explainMap);
                isSortSet = true;
                break;
            case PAY_PLAN:
//                filterArray = searchFilterHelp.getPayPlanFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getPayPlanOrder(explainMap);
                isSortSet = true;
                break;
            case ASSEMBLE:
//                filterArray = searchFilterHelp.getAssembleFilter(listAppSearchFilterDTO, explainMap);
                orderOptionPojoList = searchFilterHelp.getAssembleOrder(explainMap);
                isSortSet = true;
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
//                filterArray = searchFilterHelp.getOutstockFilter(listAppSearchFilterDTO, explainMap);
                orderOptionPojoList = searchFilterHelp.getOutstockOrder(explainMap);
                isSortSet = true;
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
//                filterArray = searchFilterHelp.getInstockFilter(listAppSearchFilterDTO, explainMap);
                orderOptionPojoList = searchFilterHelp.getInstockOrder(explainMap);
                isSortSet = true;
                break;
            case INVENTORY:
//                filterArray = searchFilterHelp.getInventoryFilter(listAppSearchFilterDTO, explainMap);
                orderOptionPojoList = searchFilterHelp.getInventoryOrder(explainMap);
                isSortSet = true;
                break;
            case TRANSFER:
//                filterArray = searchFilterHelp.getTransferFilter(listAppSearchFilterDTO, explainMap);
                orderOptionPojoList = searchFilterHelp.getTransferOrder(explainMap);
                isSortSet = true;
                break;
            case WAREHOUSE:
                if (userModel.isBoss(userEntity) || userEntity.isWarehouseManager()) {
                    // 仓库列表普通员工只能看到自己负责的 只有老板或者仓库主管才能看到所有的
//                    filterArray = searchFilterHelp.getWarehouseFilter(explainMap);
                }
                orderOptionPojoList = searchFilterHelp.getWarehouseOrder(explainMap);
                break;
            case PRODUCT:
//                filterArray = searchFilterHelp.getProductFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getProductOrder(explainMap);
                isSortSet = true;
                break;
            case STOCK_SEARCH:
                if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                    //filterArray = searchFilterHelp.getGuaranteeSearchFilter(listAppSearchFilterDTO, explainMap);
                    orderOptionPojoList = searchFilterHelp.getGuaranteeSearchOrder(explainMap);
                    listAppSearchFilterDTO.setGroupId(Long.valueOf(listGroupEnum.getCode()));
                } else {
                    if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.WARNING_SEARCH.getCode())) {
                        // 预警查询的groupId他也是用formId传过来的，所以这边做个特殊转换
                        listAppSearchFilterDTO.setGroupId(Long.valueOf(listGroupEnum.getCode()));
                    }
                    //filterArray = searchFilterHelp.getProductStockFilter(listAppSearchFilterDTO, explainMap);
                    orderOptionPojoList = searchFilterHelp.getProductOrder(explainMap);
                }
                isSortSet = true;
                break;
            case WORK_ORDER:
//                filterArray = searchFilterHelp.getWorkOrderFilter(explainMap, subBusinessType);
                orderOptionPojoList = searchFilterHelp.getWorkOrderOrder(explainMap);
                isSortSet = true;
                break;
            case WORK_ORDER_ROB:
//                filterArray = searchFilterHelp.getWorkOrderFilter(explainMap, subBusinessType);
                orderOptionPojoList = searchFilterHelp.getWorkOrderOrder(explainMap);
                isSortSet = true;
                break;
            case REFUND:
//                filterArray = searchFilterHelp.getRefundFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getRefundOrder();
                isSortSet = true;
                break;
            case PREPAYMENT_BALANCE:
//                filterArray = searchFilterHelp.getPaymentBalanceFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getPaymentBalanceOrder(explainMap);
                isSortSet = true;
                break;
            case PAYMENT_SHEET:
//                filterArray = searchFilterHelp.getPaymentSheetFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getPaymentSheetOrder(explainMap);
                isSortSet = true;
                break;
            case PREPAY_BALANCE:
//                filterArray = searchFilterHelp.getPayBalanceFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getPayBalanceOrder(explainMap);
                isSortSet = true;
                break;
            case PAY_SHEET:
//                filterArray = searchFilterHelp.getPaySheetFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getPaySheetOrder(explainMap);
                isSortSet = true;
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                isSortSet = true;
                break;
            case REIMBURSEMENT_FORM:
//                filterArray = searchFilterHelp.getReimbursementFormFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getReimbursementFormOrder(explainMap);
                isSortSet = true;
                break;
            case EXPENSE:
//                filterArray = searchFilterHelp.getExpenseFilter(explainMap);
                orderOptionPojoList = searchFilterHelp.getExpenseOrder(explainMap);
                isSortSet = true;
                break;
            case STOCK_FLOW_BILL:
            case STOCK_STANDING_BOOK:
            case BATCH_FLOW_BILL:
                //filterArray = searchFilterHelp.getStockFlowBillFilter(listAppSearchFilterDTO, explainMap);
                isSortSet = false;
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", listAppSearchFilterDTO.getCorpid());
                param.put("userId", listAppSearchFilterDTO.getUserId());
                param.put("formId", listAppSearchFilterDTO.getFormId());
                param.put("businessType", listAppSearchFilterDTO.getBusinessType());
                param.put("del", DelEnum.NORMAL.getDel());
                List<StockDateFilterEntity> stockDateFilterEntityList = stockDateFilterModel.findEntitys(param);
                if (stockDateFilterEntityList.isEmpty()) {
                    JSONObject filterContent = new JSONObject();
                    filterContent.put("timeType", TimeTypeEnum.DAY.getCode());
                    filterContent.put("timeName", TimeTypeEnum.DAY.getName());
                    filterContent.put("maxYear", 1);
                    explains.put("filterContent", filterContent);
                } else {
                    stockDateFilterEntityList.get(0).getContentData().put("maxYear", 1);
                    explains.put("filterContent", stockDateFilterEntityList.get(0).getContentData());
                }
                break;
            case MARKETING_ACTIVITY_MANAGEMENT:
            case PROMOTION_ACTIVITY_MANAGEMENT:
                JSONObject filterContent = new JSONObject();
                filterContent.put("timeType", TimeTypeEnum.YEAR.getCode());
                filterContent.put("timeName", TimeTypeEnum.YEAR.getName());
                filterContent.put("maxYear", 1);
                explains.put("filterContent", filterContent);
                break;
            case SEQ_SEARCH:
                //filterArray = searchFilterHelp.getProductSerialFlowFilter(listAppSearchFilterDTO, explainMap);

                break;
            case ALL_CLUE:
            case CLUE_PUBLIC:
            case CLUE_RECYCLE:
                orderOptionPojoList = searchFilterHelp.getClueOrder(explainMap);
                break;
            case DISTRIBUTOR_ACCOUNT:
                orderOptionPojoList = searchFilterHelp.getAccountSearchFilter(explainMap);
                isSortSet = true;
                break;
            case OTHER_INCOME:
                orderOptionPojoList = searchFilterHelp.getOtherIncomeOrder(explainMap);
                isSortSet = true;
                break;
            case OTHER_EXPENSE:
                orderOptionPojoList = searchFilterHelp.getOtherExpenseOrder(explainMap);
                isSortSet = true;
                break;
            case FUND_TRANSFER:
                orderOptionPojoList = searchFilterHelp.getFundTransferOrder(explainMap);
                isSortSet = true;
                break;
            case KNOWLEDGE_BASE:
                orderOptionPojoList = searchFilterHelp.getKnowledgeOrder(explainMap);
                isSortSet = false;
                break;
            case SMART_REPLENISHMENT:
                orderOptionPojoList = searchFilterHelp.getSmartReplenishmentOrder(explainMap);
                isSortSet = true;
                break;
            default:
                break;
        }
        AppListFilterAttrPojo listFilterAttrPojo = new AppListFilterAttrPojo();
        //if (!Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode())) {
//        listFilterAttrPojo = searchFilterHelp.getFilterList(listAppSearchFilterDTO, filterArray);
//        List<SelectPojo> selectPojoList = listFilterAttrPojo.getSelectPojoList();
//        List<String> selectedAttrList = listFilterAttrPojo.getSelectedAttrList();
//        List<SelectPojo> currentSelectPojoList = listFilterAttrPojo.getCurrentSelectPojoList();
//        if (Objects.nonNull(filterArray)) {
//            List<SelectPojo> defaultSelectPojoList = JSON.parseArray(JSON.toJSONString(filterArray), SelectPojo.class);
//            selectPojoList.removeIf(selectPojo -> searchFilterHelp.isDefaultFilterAttr(defaultSelectPojoList, selectPojo.getAttr()));
//            selectedAttrList.removeIf(attr -> searchFilterHelp.isDefaultFilterAttr(defaultSelectPojoList, attr));
//            currentSelectPojoList.removeIf(selectPojo -> searchFilterHelp.isDefaultFilterAttr(defaultSelectPojoList, selectPojo.getAttr()));
//        }
//        JSONArray currentSelectArray = JSON.parseArray(JSON.toJSONString(currentSelectPojoList));
//        if (Objects.isNull(filterArray)) {
//            filterArray = currentSelectArray;
//        } else {
//            filterArray.addAll(currentSelectArray);
//        }
       // }

        if (searchMap != null) {
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                FieldAttrEntity fieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                if(Objects.nonNull(fieldAttrEntity) && (Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ZERO) || Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ZERO))){
                    // 电话字段不可见，去除电话字段模糊搜索，暂时借用PlaceholderEnum.CUSTOMER_COMMUNICATE.getName()
                    searchMap.put(StringConstant.INIT_VALUE, PlaceholderEnum.CUSTOMER_COMMUNICATE.getName());
                }
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                FieldAttrEntity fieldAttrEntity = explainMap.get(ClueEnum.PHONE.getAttr());
                if(Objects.nonNull(fieldAttrEntity) && (Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ZERO) || Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ZERO))){
                    // 电话字段不可见，去除电话字段模糊搜索，暂时借用PlaceholderEnum.CUSTOMER_COMMUNICATE.getName()
                    searchMap.put(StringConstant.INIT_VALUE, PlaceholderEnum.CUSTOMER_COMMUNICATE.getName());
                }
            } else if (Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode())) {
                FieldAttrEntity fieldAttrEntity = explainMap.get(DistributorEnum.PHONE.getAttr());
                if(Objects.nonNull(fieldAttrEntity) && (Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ZERO) || Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ZERO))){
                    // 电话字段不可见，去除电话字段模糊搜索，暂时借用PlaceholderEnum.DISTRIBUTOR_COMMUNICATE.getName()
                    searchMap.put(StringConstant.INIT_VALUE, PlaceholderEnum.DISTRIBUTOR_COMMUNICATE.getName());
                }
            }
            //工单移动端骚操作
            if (Objects.equals(refTypeEnum.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                searchMap.put(StringConstant.INIT_VALUE, I18nMessageUtil.getMessage(I18nStringConstant.TICKET_NUMBER_SEARCH));
            } else if (Objects.equals(refTypeEnum.getCode(), XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) && DistributorMarkEnum.OTHER.getCode().equals(distributorMark)) {
                // 跟进记录搜索框提示
                searchMap.put(StringConstant.INIT_VALUE, PlaceholderEnum.CUSTOMER_COMMUNICATE.getName());
            } else if (Objects.equals(refTypeEnum.getCode(), XbbRefTypeEnum.STOCK_FLOW_BILL.getCode())  || Objects.equals(refTypeEnum.getCode(), XbbRefTypeEnum.STOCK_STANDING_BOOK.getCode())) {
                searchMap.put("productSearch", 1);
                searchMap.put("attr", StockFlowBillEnum.NAME.getAttr());
            } else if (Objects.equals(refTypeEnum.getCode(), XbbRefTypeEnum.SEQ_SEARCH.getCode())) {
                searchMap.put("attr", ProductSerialBalanceEnum.SEQ.getAttr());
            } else if (Objects.equals(refTypeEnum.getCode(), XbbRefTypeEnum.BATCH_FLOW_BILL.getCode())) {
                searchMap.put("attr", BatchFlowBillEnum.BATCH.getAttr());
            } else if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                searchMap.put("attr", SelectProductEnum.BATCH.getSaasAttr());
                searchMap.put("initValue", SelectProductEnum.BATCH.getAttrName());
            }
            explains.put("search", searchMap);
        }
//        boolean isFilterSet = filterArray != null && filterArray.size() > 0;
//        if (isFilterSet){
//            explains.put(StringConstant.FILTER, filterArray);
//        }
        // 列表页默认排序处理
        ColumnSetListDTO columnSetListDTO = new ColumnSetListDTO();
        BeanUtil.copyProperties(listAppSearchFilterDTO, columnSetListDTO);
        ColumnSetListVO columnSetListVO = userConfigService.columnSetList(columnSetListDTO);
        Map<String, Object> userConfigMap = columnSetListVO.getUserConfigMap();
        JSONObject defaultSort = new JSONObject();
        String defaultSortAttr = "";
        if (userConfigMap != null) {
            JSONObject defaultSortField = (JSONObject) userConfigMap.getOrDefault(UserConfigEnum.DEFAULT_SORT_FIELD.getAlias(), new JSONObject());
            if (!defaultSortField.isEmpty() && defaultSortField.get("sortAttr") != null && defaultSortField.get("sortType") != null) {
                //默认排序attr
                defaultSortAttr = defaultSortField.get("sortAttr").toString();
                defaultSort.put("sortAttr", defaultSortAttr);
                if (explainMap.containsKey(defaultSortAttr)) {
                    // 默认排序中文名
                    defaultSort.put("sortName", explainMap.get(defaultSortAttr).getAttrName());
                } else if (GuaranteeExplainConstant.GUARANTEE_EXPLAIN.contains(defaultSortAttr) || Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                    // 批次保质期查询新增字段不在产品解释中
                    SelectProductEnum selectProductEnum = SelectProductEnum.getAttrBySaasAttr(defaultSortAttr);
                    defaultSort.put("sortName", selectProductEnum.getAttrName());
                }else if (Objects.equals(listAppSearchFilterDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode()) && Objects.equals(listAppSearchFilterDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(defaultSortAttr, ProductEnum.STOCK.getAttr())){
                    defaultSort.put("sortName", "待入库数量");
                }
                // 智能补货列表排序字段回显
                if (Objects.equals(XbbRefTypeEnum.SMART_REPLENISHMENT,refTypeEnum)){
                    String attrName = "";
                    if (Objects.equals(SelectProductEnum.PRODUCT.getAttr(),defaultSortAttr)){
                        defaultSort.put("sortName", SelectProductEnum.PRODUCT.getAttrName());
                    }else if (Objects.equals("serialNo",defaultSortAttr)){
                        defaultSort.put("sortName", SelectProductEnum.PRODUCT_NO.getAttrName());
                    }else if (Objects.equals(SelectProductEnum.STOCK.getAttr(),defaultSortAttr)){
                        defaultSort.put("sortName", SelectProductEnum.STOCK.getAttrName());
                    }else if (Objects.equals("waitOutstockNum",defaultSortAttr)){
                        defaultSort.put("sortName",ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttrName());
                    }else if (Objects.equals("miniNum",defaultSortAttr)){
                        defaultSort.put("sortName", SmartReplenishmentEnum.MINI_NUM.getAttrName());
                    }
                }
                // 默认排序type，desc和asc
                defaultSort.put("sortType", defaultSortField.get("sortType").toString());
            } else {
                if (explainMap.containsKey(StringConstant.UPDATE_TIME)) {
                    defaultSortAttr = StringConstant.UPDATE_TIME;
                    defaultSort.put("sortName", explainMap.get(StringConstant.UPDATE_TIME).getAttrName());
                    defaultSort.put("sortAttr", defaultSortAttr);
                    defaultSort.put("sortType", "desc");
                }
            }
        } else {
            if (explainMap.containsKey(StringConstant.UPDATE_TIME)) {
                // 默认排序为更新时间倒序
                defaultSortAttr = StringConstant.UPDATE_TIME;
                defaultSort.put("sortAttr", defaultSortAttr);
                defaultSort.put("sortName", explainMap.get(StringConstant.UPDATE_TIME).getAttrName());
                defaultSort.put("sortType", "desc");
            }
            if (Objects.equals(businessType, XbbRefTypeEnum.STOCK_FLOW_BILL.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.BATCH_FLOW_BILL.getCode())) {
                // 默认排序为更新时间倒序
                defaultSortAttr = StockFlowBillEnum.TIME.getAttr();
                defaultSort.put("sortAttr", defaultSortAttr);
                defaultSort.put("sortName", explainMap.get(StockFlowBillEnum.TIME.getAttr()).getAttrName());
                defaultSort.put("sortType", "asc");
            } else if (Objects.equals(businessType, XbbRefTypeEnum.SEQ_SEARCH.getCode())) {
                defaultSortAttr = ProductSerialBalanceEnum.TIME.getAttr();
                defaultSort.put("sortAttr", defaultSortAttr);
                defaultSort.put("sortName", explainMap.get(ProductSerialBalanceEnum.TIME.getAttr()).getAttrName());
                defaultSort.put("sortType", "desc");
            } else if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                defaultSortAttr = SelectProductEnum.EXPIRE_DATE.getSaasAttr();
                defaultSort.put("sortAttr", defaultSortAttr);
                defaultSort.put("sortName", SelectProductEnum.EXPIRE_DATE.getAttrName());
                defaultSort.put("sortType", "desc");
            }
        }
        // 如果选了默认排序，那么就将它从写死的排序中移除
        final String finalSortAttr = defaultSortAttr;
        if (defaultSortAttr != null && !Objects.equals(defaultSortAttr, "")) {
            orderOptionPojoList.removeIf(item -> item.getAttr() != null && item.getAttr().equals(finalSortAttr));
        }
        orderArray = JSON.parseArray(JSON.toJSONString(orderOptionPojoList));
        if (orderArray != null && orderArray.size() > 0){
            explains.put("order", orderArray);
        }
        if (defaultSort.size() > 0){
            explains.put("defaultSort", defaultSort);
        }

        if (specialFilterArray != null && specialFilterArray.size() > 0) {
            explains.put("specialFilter", specialFilterArray);
        }
        if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(),businessType) && Objects.equals(XbbRefTypeEnum.WAIT_PURCHASE.getCode(),subBusinessType)){
            explains.put("defaultSort", "");
            explains.put("order", "");
        }
        SearchFilterVO searchFilterVO = new SearchFilterVO();
        searchFilterVO.setExplains(explains);
        searchFilterVO.setSortSetFlag(isSortSet);
//        searchFilterVO.setSetFlag(isFilterSet);
        searchFilterVO.setListSearchSet(listFilterAttrPojo);
        return searchFilterVO;
    }

    @Override
    public PaasFormDataEsListVO opportunityList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        CRMMenuEnum crmMenuEnum = CRMMenuEnum.getByCode(subBusinessType);
        if (crmMenuEnum == null){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return commonListQry.execute(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO supplierCommunicateList(FormDataListDTO formDataListDTO) throws XbbException {
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(formDataListDTO.getConditions(),formDataListDTO.getLoginUser(),XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(), formDataListDTO.getSubBusinessType());
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(formDataListDTO.getConditions(), userEntity, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        supplierCommunicateService.setCondition(formDataListDTO);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formDataListDTO.getFormId(), formDataListDTO.getCorpid());
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
        explainList.forEach((item) -> {
            explainMap.put(item.getAttr(), item);
        });
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO customerCommunicateList(FormDataListDTO formDataListDTO) throws XbbException {
        saasListDataPermissionHelp.listDataPermission(formDataListDTO.getConditions(), formDataListDTO.getLoginUser(),XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(), formDataListDTO.getSubBusinessType());
        customerCommunicateService.setCondition(formDataListDTO);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formDataListDTO.getFormId(), formDataListDTO.getCorpid());
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (notExport){
            paasFormDataEsListVO.setExplainMap(new HashMap<>());
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO delCustomerList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        if (!Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return commonListQry.execute(formDataListDTO);
//        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
//        saasListDataPermissionHelp.listDataPermission(conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formDataListDTO.getSubBusinessType());
//        formDataListDTO.setConditions(conditionList);
//        formDataListDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
//        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
//        if (!Objects.equals(formDataListDTO.getFromExport(),1)){
//            paasFormDataEsListVO.setExplainMap(new HashMap<>());
//        }
//        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO delClueList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        if (!Objects.equals(subBusinessType,XbbRefTypeEnum.CLUE_RECYCLE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return commonListQry.execute(formDataListDTO);
//        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
//        saasListDataPermissionHelp.listDataPermission(conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.CLUE.getCode(), formDataListDTO.getSubBusinessType());
//        formDataListDTO.setConditions(conditionList);
//        formDataListDTO.setBusinessType(XbbRefTypeEnum.CLUE.getCode());
//        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
//        if (!Objects.equals(formDataListDTO.getFromExport(),1)){
//            paasFormDataEsListVO.setExplainMap(new HashMap<>());
//        }
//        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO publicClue(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CLUE_PUBLIC.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }

        return publicPoolListQry.publicPoolExecute(formDataListDTO);
//        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
//        UserEntity userEntity = new UserEntity();
//        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.CLUE.getCode(), formDataListDTO.getSubBusinessType());
//        // app端筛选筛选
//        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.CLUE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
//        formDataListDTO.setConditions(conditionList);
//
//        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO waitInstockList(FormDataListDTO formDataListDTO) throws XbbException{
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        if (!Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        Integer businessType = formDataListDTO.getBusinessType();
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        if (Objects.equals(businessType,XbbRefTypeEnum.PURCHASE.getCode())){
            //合同维度列表
            formDataListDTO.getConditions().addAll(saasListHelp.packageWaitInstockCondition(formDataListDTO));
            paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        }else if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode())){
            //获得采购产品关联表查询参数
            Map<String, Object> param = getPurchaseProductParam(formDataListDTO);
            List<PurchaseProductEntity> purchaseProductEntity = purchaseProductService.findProductEntitys(formDataListDTO,param);
            if (Objects.isNull(purchaseProductEntity)){
                throw new XbbException(ProductErrorCodeEnum.API_ERROR_205116);
            }
            paasFormDataEsListVO = paasFormDataService.purchaseIdListByEs(formDataListDTO,purchaseProductEntity,param);
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO waitOutstockList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        if (!Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())) {
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        if (Objects.isNull(formDataListDTO.getPage()) || Objects.isNull(formDataListDTO.getPageSize())) {
            throw new XbbException(ThirdPartyUsageErrorCodeEnum.API_ERROR_900005, String.format(ThirdPartyUsageErrorCodeEnum.API_ERROR_900005.getMsg(), "分页参数"));
        }
        // 待出库可见权限
        UserVO loginUser = formDataListDTO.getLoginUser();
        if (!loginUser.getPermSet().contains(ProPermissionAliasEnum.PENDING_OUTSTOCK_VIEW.getAlias()) && !loginUser.isAdminOrBoss()) {
            throw new XbbException(PurchaseErrorCodeEnum.API_ERROR_225038);
        }
        Integer businessType = formDataListDTO.getBusinessType();
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList = conditionList == null ? new ArrayList<>() : conditionList;
        //如果是出库退货单中关联订货单，这个订货单的订单状态有要求,订单状态必须为待发货
        if (Objects.equals(formDataListDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(OrderEnum.STATUS.getAttr(), "", OrderEnum.STATUS.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(OrderStatusEnum.DELIVERED.getCode()));
            conditionList.add(conditionsEntityExt);
        }
        conditionList.addAll(saasListHelp.packageWaitOutstockCondition(formDataListDTO));
        if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
            //合同维度列表
            paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
            //产品维度列表
            paasFormDataEsListVO = paasFormDataService.productViewListByEs(formDataListDTO);
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO contractList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return commonListQry.execute(formDataListDTO);
//        if (Objects.equals(formDataListDTO.getFromExport(),1) || Objects.equals(PlatFormEnum.DINGTALK.getValue(), formDataListDTO.getPlatform())) {
//
//            setStatusFilter(formDataListDTO, ContractEnum.ARCHIVED.getAttr());
//            List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
//            conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(), formDataListDTO.getCorpid(), formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
//            UserEntity userEntity = new UserEntity();
//            BeanUtil.copyProperties(formDataListDTO.getLoginUser(), userEntity);
//            saasListDataPermissionHelp.listDataPermission(conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.CONTRACT.getCode(), formDataListDTO.getSubBusinessType());
//            // app端范围筛选
//            saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.CONTRACT.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
//            formDataListDTO.setConditions(conditionList);
//            PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
//            if (!Objects.equals(formDataListDTO.getFromExport(),1)){
//                paasFormDataEsListVO.setExplainMap(new HashMap<>());
//            }
//            return paasFormDataEsListVO;
//        }
//        AbstractWebDataAnalysisHandle abstractWebDataAnalysisHandle = webDataAnalysisFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
//        PaasFormDataEsListVO paasFormDataEsListVO = abstractWebDataAnalysisHandle.analysisData(formDataListDTO);
//        if (!Objects.equals(formDataListDTO.getFromExport(),1)){
//            paasFormDataEsListVO.setExplainMap(new HashMap<>());
//        }
//        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO orderList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        formDataListDTO.setBusinessType(XbbRefTypeEnum.ORDER.getCode());
        formDataListDTO.setSubBusinessType(XbbRefTypeEnum.ORDER.getCode());
        AbstractWebDataAnalysisHandle abstractWebDataAnalysisHandle = webDataAnalysisFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        PaasFormDataEsListVO paasFormDataEsListVO = abstractWebDataAnalysisHandle.analysisData(formDataListDTO);
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (notExport){
            paasFormDataEsListVO.setExplainMap(new HashMap<>());
        }
        paasFormDataEsListVO.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO supplierList(FormDataListDTO formDataListDTO) throws XbbException{
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.SUPPLIER.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.SUPPLIER.getCode(), formDataListDTO.getSubBusinessType());
        // 共享权限处理
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.SUPPLIER.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO purchaseList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.PURCHASE.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.PURCHASE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        // TODO 导出暂时不处理权限
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (!notExport) {
            return paasFormDataEsListVO;
        }
        List<ButtonPojo> buttonPojoList = paasFormDataEsListVO.getTopPermissions();
        if (buttonPojoList != null) {
            for (ButtonPojo buttonPojo : buttonPojoList){
                if (Objects.equals(buttonPojo.getAttr(),SaasButtonEnum.WAIT_PURCHASE.getAttr())){
                    PaasAppEntity paasAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.JXC.getAlias(),formDataListDTO.getCorpid());
                    ButtonExtraPojo buttonExtraPojo = new ButtonExtraPojo();
                    buttonExtraPojo.setAppId(paasAppEntity.getId());
                    buttonExtraPojo.setSubBusinessType(XbbRefTypeEnum.WAIT_PURCHASE.getCode());
                    buttonExtraPojo.setHasNumber(false);
                    buttonPojo.setButtonExtra(buttonExtraPojo);
                    break;
                }
            }
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO returnedPurchaseList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.RETURNED_PURCHASE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.RETURNED_PURCHASE.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.RETURNED_PURCHASE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO bombillList(FormDataListDTO formDataListDTO) throws XbbException{
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.BOM_BILL.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.BOM_BILL.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.BOM_BILL.getCode(), formDataListDTO.getSubBusinessType());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO productionOrderList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCTION_ORDER.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.PRODUCTION_ORDER.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.PRODUCTION_ORDER.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        List<ButtonPojo> buttonPojoList = paasFormDataEsListVO.getTopPermissions();
        if (Objects.nonNull(buttonPojoList)) {
            for (ButtonPojo buttonPojo : buttonPojoList) {
                if (Objects.equals(buttonPojo.getAttr(), SaasButtonEnum.WAIT_PRODUCE.getAttr())) {
                    PaasAppEntity paasAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.CRM.getAlias(), formDataListDTO.getCorpid());
                    ButtonExtraPojo buttonExtraPojo = new ButtonExtraPojo();
                    buttonExtraPojo.setAppId(paasAppEntity.getId());
                    buttonExtraPojo.setSubBusinessType(XbbRefTypeEnum.WAIT_PRODUCE.getCode());
                    buttonPojo.setButtonExtra(buttonExtraPojo);
                    buttonExtraPojo.setHasNumber(true);
                    break;
                }
            }
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO assembleList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.ASSEMBLE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.ASSEMBLE.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.ASSEMBLE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO instockList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.INSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE_INSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.REFUND_INSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.OTHER_INSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.INSTOCK.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.INSTOCK.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (!notExport) {
            return paasFormDataEsListVO;
        }
        List<ButtonPojo> buttonPojoList = paasFormDataEsListVO.getTopPermissions();
        for (ButtonPojo buttonPojo : buttonPojoList){
            if (Objects.equals(buttonPojo.getAttr(),SaasButtonEnum.WAIT_INSTOCK.getAttr())){
                PaasAppEntity paasAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.JXC.getAlias(),formDataListDTO.getCorpid());
                ButtonExtraPojo buttonExtraPojo = new ButtonExtraPojo();
                buttonExtraPojo.setAppId(paasAppEntity.getId());
                buttonExtraPojo.setSubBusinessType(XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode());
                buttonPojo.setButtonExtra(buttonExtraPojo);
                buttonExtraPojo.setHasNumber(true);
                break;
            }
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO outstockList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.OUTSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.ORDER_OUTSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())
                && !Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.OUTSTOCK.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.OUTSTOCK.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (!notExport) {
            return paasFormDataEsListVO;
        }
        List<ButtonPojo> buttonPojoList = paasFormDataEsListVO.getTopPermissions();
        for (ButtonPojo buttonPojo : buttonPojoList){
            if (Objects.equals(buttonPojo.getAttr(),SaasButtonEnum.WAIT_OUTSTOCK.getAttr())){
                PaasAppEntity paasAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.CRM.getAlias(),formDataListDTO.getCorpid());
                ButtonExtraPojo buttonExtraPojo = new ButtonExtraPojo();
                buttonExtraPojo.setAppId(paasAppEntity.getId());
                buttonExtraPojo.setSubBusinessType(XbbRefTypeEnum.WAIT_OUTSTOCK.getCode());
                buttonExtraPojo.setDistributorMark(formDataListDTO.getDistributorMark());
                buttonPojo.setButtonExtra(buttonExtraPojo);
                buttonExtraPojo.setHasNumber(true);
                break;
            }
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO transferList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.TRANSFER.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.TRANSFER.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.TRANSFER.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO inventoryList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.INVENTORY.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.INVENTORY.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.INVENTORY.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO invoiceList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.INVOICE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        if(Objects.isNull(formDataListDTO.getListGroupId())){
            formDataListDTO.setListGroupId(0L);
        }
        if(Objects.isNull(formDataListDTO.getDefaultGroup())){
            formDataListDTO.setDefaultGroup(BasicConstant.ONE);
        }
        formDataListDTO.setStatusFilter(saasListHelp.invoiceSetStatusFilterHandle(formDataListDTO.getListGroupId()));
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.INVOICE.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);

        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.INVOICE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        //在fieldAttrEntity 里新增 作废金额会划横线 cancelFlag 来 控制 如果不是作废 直接 跳过 返回结果
        if(Objects.equals(formDataListDTO.getStatusFilter(),BasicConstant.TWO) || Objects.equals(formDataListDTO.getStatusFilter(),BasicConstant.ZERO)) {
            List<FieldAttrEntity> headList = paasFormDataEsListVO.getHeadList();
            for(FieldAttrEntity fieldAttrEntity : headList) {
                if(Objects.equals(fieldAttrEntity.getAttr(), InvoiceEnum.TOTAL_MONEY.getAttr())){
                    fieldAttrEntity.setCancelFlag(BasicConstant.ONE);
                }
            }
            paasFormDataEsListVO.setHeadList(headList);
        }
        if(Objects.equals(formDataListDTO.getStatusFilter(),BasicConstant.ONE) || Objects.equals(formDataListDTO.getStatusFilter(),BasicConstant.ZERO)) {
            List<PaasFormDataEntityExt> paasFormDataEntityExts =paasFormDataEsListVO.getPaasFormDataESList();
            if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)){
                for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts){
                    JSONObject data = paasFormDataEntityExt.getData();
                    if (Objects.isNull(data)) {
                        continue;
                    }
                    Integer isRed = data.getInteger(InvoiceEnum.IS_RED.getAttr());
                    if(Objects.equals(isRed,BasicConstant.ONE)){
                        data.put("isRed",isRed);
                    }
                }
            }
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO purchaseInvoiceList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        if(Objects.isNull(formDataListDTO.getListGroupId())){
            formDataListDTO.setListGroupId(0L);
        }
        if(Objects.isNull(formDataListDTO.getDefaultGroup())){
            formDataListDTO.setDefaultGroup(BasicConstant.ONE);
        }
        formDataListDTO.setStatusFilter(saasListHelp.invoiceSetStatusFilterHandle(formDataListDTO.getListGroupId()));
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        //在fieldAttrEntity 里新增 作废金额会划横线 cancelFlag 来 控制 如果不是作废 直接 跳过 返回结果
        if(Objects.equals(formDataListDTO.getStatusFilter(),BasicConstant.TWO) || Objects.equals(formDataListDTO.getStatusFilter(),BasicConstant.ZERO)) {
            List<FieldAttrEntity> headList = paasFormDataEsListVO.getHeadList();
            for(FieldAttrEntity fieldAttrEntity : headList) {
                if(Objects.equals(fieldAttrEntity.getAttr(), PurchaseInvoiceEnum.TOTAL_MONEY.getAttr())){
                    fieldAttrEntity.setCancelFlag(BasicConstant.ONE);
                }
            }
            paasFormDataEsListVO.setHeadList(headList);
        }
        if(Objects.equals(formDataListDTO.getStatusFilter(),BasicConstant.ONE) || Objects.equals(formDataListDTO.getStatusFilter(),BasicConstant.ZERO)) {
            List<PaasFormDataEntityExt> paasFormDataEntityExts =paasFormDataEsListVO.getPaasFormDataESList();
            if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)){
                for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts){
                    JSONObject data = paasFormDataEntityExt.getData();
                    if (Objects.isNull(data)) {
                        continue;
                    }
                    Integer isRed = data.getInteger(PurchaseInvoiceEnum.IS_RED.getAttr());
                    if(Objects.equals(isRed,BasicConstant.ONE)){
                        data.put("isRed",isRed);
                    }
                }
            }
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO creditLimitList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer businessType = formDataListDTO.getBusinessType();
        if (!Objects.equals(businessType, XbbRefTypeEnum.CREDIT_LIMIT.getCode())) {
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(), userEntity);
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(), formDataListDTO.getCorpid(), formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        saasListDataPermissionHelp.listDataPermission(conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.CREDIT_LIMIT.getCode(), formDataListDTO.getSubBusinessType());
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.CREDIT_LIMIT.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    /**
     * 固定额度列表
     * @param formDataListDTO 参数
     * @return 固定额度列表
     * @throws XbbException XbbException
     * @author xingxing.xiao
     */
    @Override
    public PaasFormDataEsListVO creditFixedLimitList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer businessType = formDataListDTO.getBusinessType();
        if (!Objects.equals(businessType, XbbRefTypeEnum.CREDIT_FIXED_LIMIT.getCode())) {
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(), userEntity);
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(), formDataListDTO.getCorpid(), formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        saasListDataPermissionHelp.listDataPermission(conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.CREDIT_FIXED_LIMIT.getCode(), formDataListDTO.getSubBusinessType());
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.CREDIT_FIXED_LIMIT.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    /**
     * 临时额度列表
     * @param formDataListDTO 参数
     * @return 临时额度列表
     * @throws XbbException XbbException
     * @author xingxing.xiao
     */
    @Override
    public PaasFormDataEsListVO creditTemporaryLimitList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer businessType = formDataListDTO.getBusinessType();
        if (!Objects.equals(businessType, XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode())) {
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(), userEntity);
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(), formDataListDTO.getCorpid(), formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        saasListDataPermissionHelp.listDataPermission(conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode(), formDataListDTO.getSubBusinessType());
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        // 申请状态处理
        for (ConditionsEntityExt conditionsEntityExt : conditionList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), CreditTemporaryLimitEnum.APPLY_STATUS.getAttr())) {
                String value = (String) conditionsEntityExt.getValue().get(0);
                if (Objects.equals(value, CreditTemporaryApplyStatusEnum.NORMAL.getCode())) {
                    // 生效中
                    ConditionsEntityExt condition = new ConditionsEntityExt();
                    condition = new ConditionsEntityExt();
                    condition.setAttr(CreditTemporaryLimitEnum.END_TIME.getAttr());
                    condition.setFieldType(CreditTemporaryLimitEnum.END_TIME.getFieldType());
                    condition.setSymbol(ConditionEnum.GREATEREQUAL.getSymbol());
                    condition.setValue(Arrays.asList(DateTimeUtil.getTodayInt()));
                    conditionList.add(condition);
                } else if (Objects.equals(value, CreditTemporaryApplyStatusEnum.EXPIRED.getCode())) {
                    // 已过期
                    conditionsEntityExt.setValue(Arrays.asList(CreditTemporaryApplyStatusEnum.NORMAL.getCode()));
                    ConditionsEntityExt condition = new ConditionsEntityExt();
                    condition = new ConditionsEntityExt();
                    condition.setAttr(CreditTemporaryLimitEnum.END_TIME.getAttr());
                    condition.setFieldType(CreditTemporaryLimitEnum.END_TIME.getFieldType());
                    condition.setSymbol(ConditionEnum.LESSTHAN.getSymbol());
                    condition.setValue(Arrays.asList(DateTimeUtil.getTodayInt()));
                    conditionList.add(condition);
                }

                break;
            }
        }

        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    /**
     * 信用流水列表
     * @param formDataListDTO 参数
     * @return 信用流水列表
     * @throws XbbException XbbException
     */
    @Override
    public PaasFormDataEsListVO creditCardBillLimitList(FormDataListDTO formDataListDTO) throws XbbException {
        return null;
    }

    @Override
    public PaasFormDataEsListVO paymentList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PAYMENT.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        //应收款特殊来源单据条件解析
        List<ConditionsEntityExt> newConditionList = saasListHelp.parseCommonFilter(formDataListDTO,conditionList);
        newConditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, newConditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.PAYMENT.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(newConditionList, userEntity, XbbRefTypeEnum.PAYMENT.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(newConditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO payPlanList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PAY_PLAN.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.PAY_PLAN.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.PAY_PLAN.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public NearCustomerListVO nearCustomerList(NearCustomerDTO nearCustomerDTO) throws XbbException{
        if (!Objects.equals(nearCustomerDTO.getSubBusinessType(),XbbRefTypeEnum.CUSTOMER_NEARBY.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        nearCustomerDTO.setDistancePower(DistanceEnum.getByCode(nearCustomerDTO.getDistance()));
        nearCustomerDTO.setIsArchived(1);
        SearchHits hits = getNearCustomerEsList(nearCustomerDTO);
        String corpid = nearCustomerDTO.getCorpid();
        List<NearCustomerPojo> list = new ArrayList<>();
        Map<String,String> typeMap = dataDictionaryModel.getDictionaryMap(DictionaryEnum.CUSTOMER_STATUS,corpid,nearCustomerDTO.getFormId());

        List<Long> dataIdIn = new ArrayList<>();
        for (SearchHit hit : hits) {
            PaasFormDataEntityExt entity = JSONObject.parseObject(hit.getSourceAsString(),PaasFormDataEntityExt.class);
            JSONObject data = entity.getData();
            NearCustomerPojo nearCustomerPojo = new NearCustomerPojo();
            nearCustomerPojo.setId(entity.getDataId());
            nearCustomerPojo.setName(data.getString(CustomerManagementEnum.NAME.getAttr()));
            nearCustomerPojo.setLastConnectTime(data.getInteger(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr()));
            nearCustomerPojo.setLastConnectTimeStr(DateTimeUtil.getLastConnectTimeStr(data.getLong(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr())));
            nearCustomerPojo.mergeAddress(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()));
            nearCustomerPojo.setType(typeMap.getOrDefault(data.getString(CustomerManagementEnum.TYPE.getAttr()),I18nMessageUtil.getMessage(CommonConstant.NOT_SET)));
            Double distance = Double.valueOf(hit.getSortValues()[0].toString());
            distance = distance == null ? -1D : distance;
            distance = distance.isInfinite() ? -1D : distance;
            nearCustomerPojo.setDistance(distance);
            if (distance >= 0){
                nearCustomerPojo.setLatitude(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()).getJSONObject(FieldTypeEnum.LOCATION.getAlias()).getDouble("lat"));
                nearCustomerPojo.setLongitude(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()).getJSONObject(FieldTypeEnum.LOCATION.getAlias()).getDouble("lon"));
            }
            nearCustomerPojo.setIsPublic(data.getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr()));
            nearCustomerPojo.setIsArchived(data.getInteger(CustomerManagementEnum.IS_ARCHIVED.getAttr()));
            nearCustomerPojo.setTagData(new JSONObject());
            dataIdIn.add(entity.getDataId());

            list.add(nearCustomerPojo);
        }

        Map<Long,String> publicTagMap = tagLinkModel.getPublicTag(corpid, dataIdIn);
        String publicTag = CustomerManagementEnum.NAME.getSaasAttr() + "Tag";
        String archivedTag = CustomerManagementEnum.NAME.getSaasAttr() + "Tag";
        for (NearCustomerPojo nearCustomerPojo : list) {
            Long id = nearCustomerPojo.getId();

            if (Objects.equals(nearCustomerPojo.getIsArchived(), ArchivedEnum.ARCHIVED.getCode())) {
                JSONObject tagData = nearCustomerPojo.getTagData();
                tagData = tagData == null ? new JSONObject() : tagData;
                JSONArray tagPojoList = tagData.getJSONArray(archivedTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                tagPojoList.add(new TagPojo(TagEnum.TAG_ARCHIVED));
                tagData.put(archivedTag, tagPojoList);
                nearCustomerPojo.setTagData(tagData);
            }

            if (publicTagMap.containsKey(id)) {
                JSONObject tagData = nearCustomerPojo.getTagData();
                tagData = tagData == null ? new JSONObject() : tagData;
                JSONArray tagPojoList = tagData.getJSONArray(publicTag);
                tagPojoList = tagPojoList == null ? new JSONArray() : tagPojoList;
                TagPojo tagPojo = new TagPojo(TagEnum.TAG_RETURN_PUBLIC);
                tagPojo.setMemo(publicTagMap.get(id));
                tagPojoList.add(tagPojo);
                tagData.put(publicTag, tagPojoList);
                nearCustomerPojo.setTagData(tagData);
            }
        }

        NearCustomerListVO nearCustomerListVO = new NearCustomerListVO();
        nearCustomerListVO.setList(list);
        PageHelper pageHelper = new PageHelper(nearCustomerDTO.getPage(),nearCustomerDTO.getPageSize());
        pageHelper.setRowsCount((int) hits.getTotalHits().value);
        nearCustomerListVO.setPageHelper(pageHelper);
        List<ListTopButtonEnum> topButtonEnumList = ListTopButtonEnum.getByBusinessType(XbbRefTypeEnum.CUSTOMER_NEARBY.getCode());
        List<ButtonPojo> topButtonList = new ArrayList<>();
        for (ListTopButtonEnum topButtonEnum : topButtonEnumList) {
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(topButtonEnum.getAnEnum(), buttonPojo);
            if (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.EXPORT.getAttr())) {
                List<ButtonPojo> subButtonList = new ArrayList<ButtonPojo>(){{
                    add(new ButtonPojo(){{BeanUtil.copyProperties(topButtonEnum.getAnEnum(), this);}});
                }};
                List<SaasSubButtonEnum> saasSubButtonEnumList = SaasSubButtonEnum.getByPermissionAlias(nearCustomerDTO.getSubBusinessType(),topButtonEnum,nearCustomerDTO.getLoginUser().getPermSet());
                saasSubButtonEnumList.forEach(item->{
                    subButtonList.add(new ButtonPojo(){{setAttr(item.getAlias());setValue(item.getName());}});
                });
                buttonPojo.setSubButtons(subButtonList);
            }
            topButtonList.add(buttonPojo);
        }
        nearCustomerListVO.setTopPermissions(topButtonList);
        return nearCustomerListVO;
    }

    @Override
    public PaasFormDataEsListVO nearCustomerList4Export(NearCustomerDTO nearCustomerDTO) throws XbbException{
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        if (!Objects.equals(nearCustomerDTO.getSubBusinessType(),XbbRefTypeEnum.CUSTOMER_NEARBY.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        nearCustomerDTO.setDistancePower(DistanceEnum.getByCode(nearCustomerDTO.getDistance()));
        nearCustomerDTO.setIsArchived(1);
        SearchHits hits = getNearCustomerEsList(nearCustomerDTO);
        String corpid = nearCustomerDTO.getCorpid();
        List<PaasFormDataEntityExt> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            PaasFormDataEntityExt entity = JSONObject.parseObject(hit.getSourceAsString(),PaasFormDataEntityExt.class);
            list.add(entity);
        }
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(nearCustomerDTO.getFormId(), corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String,FieldAttrEntity> explainMap = paasFormExplainService.getExpalinMap(explainList, paasFormExplainEntity.getBusinessType(), corpid, nearCustomerDTO.getFormId());
        paasFormDataEsListVO.setExplainMap(explainMap);
        paasFormDataEsListVO.setPaasFormDataESList(list);
        return paasFormDataEsListVO;
    }

    @Override
    public SearchHits getNearCustomerEsList(NearCustomerDTO nearCustomerDTO) throws XbbException{
        //TODO haibin.zhang 附近客户查询写成这鸟样真是罪过，web\app\签到3处调用，主要是需要经纬度查询的封装，期待更优解
        String corpid = nearCustomerDTO.getCorpid();
        boolean isPublic = Objects.equals(1,nearCustomerDTO.getIsPublic());
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(nearCustomerDTO,formDataListDTO);
        saasListHelp.addressSearchCondition(formDataListDTO);
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList = conditionList == null ? new ArrayList<>() : conditionList;
        List<ConditionsEntityExt> groupConditionsList = new ArrayList<>();
        if (isPublic) {
            // 公海分组相关
            formDataListDTO.setDefaultGroup(2);
        }
        List<List<ConditionsEntityExt>> shouldConditionList = new ArrayList<>();
        saasListHelp.packageGroupList(formDataListDTO,groupConditionsList,shouldConditionList);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        saasListHelp.addressSearchShouldCondition(formDataListDTO);
        EsUtil.parseShouldCondition(boolQueryBuilder,shouldConditionList,"",corpid,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        conditionList.addAll(groupConditionsList);

        // 数据权限
        List<ConditionsEntityExt> permissionConditions = new ArrayList<>();
        if (!isPublic) {
            permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, nearCustomerDTO.getLoginUser(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), nearCustomerDTO.getSubBusinessType());
        }
        rangeScreen(nearCustomerDTO, conditionList);
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        if (Objects.equals(nearCustomerDTO.getPlatform(),StringConstant.PLATFORM_WEB)){
            if (!Objects.isNull(nearCustomerDTO.getType()) && !nearCustomerDTO.getType().isEmpty()){
                boolQueryBuilder.filter(termsQuery("data." + CustomerManagementEnum.TYPE.getAttr(),nearCustomerDTO.getType()));
            }
            if (!Objects.isNull(nearCustomerDTO.getLastConnectTime()) && nearCustomerDTO.getLastConnectTime().size() == 2){
                //TODO haibin.zhang 皮皮虾代码，后续优化
                RangeQueryBuilder rangeQueryBuilder = rangeQuery("data." + CustomerManagementEnum.LAST_CONNECT_TIME.getAttr()).gte(nearCustomerDTO.getLastConnectTime().getLong(0) / 1000);
                // 前端传参为yyyy-MM-dd 格式，所以最后一天需要精确到23:59:59，为了兼容时间戳和字符串格式，做出以下写法
                if (nearCustomerDTO.getLastConnectTime().get(1) instanceof String) {
                    String lastTime = nearCustomerDTO.getLastConnectTime().getString(1) + " 23:59:59";
                    nearCustomerDTO.getLastConnectTime().add(1, lastTime);
                    boolQueryBuilder.filter(rangeQueryBuilder.lt(nearCustomerDTO.getLastConnectTime().getLong(1)/1000));
                } else {
                    boolQueryBuilder.filter(rangeQueryBuilder.lt(nearCustomerDTO.getLastConnectTime().getLong(1)/1000));
                }
            }
            boolQueryBuilder.filter(termQuery("data." + CustomerManagementEnum.IS_PUBLIC.getAttr(),nearCustomerDTO.getIsPublic()));
        }
        if (!Objects.isNull(nearCustomerDTO.getNameLike()) && !nearCustomerDTO.getNameLike().isEmpty()){
            EsUtil.setNameLike(BasicConstant.ONE, nearCustomerDTO.getNameLike(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), false, boolQueryBuilder,true,null, null);
        }

        if (!Objects.isNull(nearCustomerDTO.getIsArchived())){
            boolQueryBuilder.filter(termQuery("data." + CustomerManagementEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode()));
        }
        EsUtil.parseCondition(boolQueryBuilder,conditionList,"",corpid,nearCustomerDTO.getBusinessType());
        Double lon = nearCustomerDTO.getLongitude();
        Double lat = nearCustomerDTO.getLatitude();
        if (Objects.isNull(lat) || Objects.isNull(lon)){
            //前端没传经纬度，就定位到天安门
            lon = 116.2327D;
            lat = 39.5427D;
        }
        boolQueryBuilder.filter(termQuery("corpid.keyword",nearCustomerDTO.getCorpid() ));

        //如果是客户签到，则去查下用户客户权限 ji
        if (Objects.equals(nearCustomerDTO.getIsNewSignIn(),1)){
            Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID,nearCustomerDTO.getCorpid());
            param.put("businessType",XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            param.put("del",0);
            param.put("enable",1);
            List<PaasFormEntityExt> paasFormEntityList = paasFormModel.findEntitys(param);
            paasFormService.removeByPermission(paasFormEntityList, nearCustomerDTO.getLoginUser());
            List<Long> formIds = new ArrayList<>();
            paasFormEntityList.forEach(item->{
                formIds.add(item.getId());
            });
            if (formIds.isEmpty()) {
                formIds.add(-1L);
            }
            boolQueryBuilder.filter(termsQuery("formId",formIds));

            ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, formIds, formDataListDTO.getLoginUser());
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, sharePermission, corpid, nearCustomerDTO.getBusinessType(), formDataListDTO.getFromThrough());
        }else {
            if (!Objects.isNull(nearCustomerDTO.getFormId())){
                boolQueryBuilder.filter(termQuery("formId",nearCustomerDTO.getFormId()));
                if (!isPublic) {
                    ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(nearCustomerDTO.getFormId()), nearCustomerDTO.getLoginUser());
                    EsUtil.parseSharePermissionCondition(boolQueryBuilder, sharePermission, corpid, nearCustomerDTO.getBusinessType(), formDataListDTO.getFromThrough());
                }
            }
        }
        //审批
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(),Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(),FlowStatusEnum.PASS.getType())));
        Integer distancePower = nearCustomerDTO.getDistancePower();
        if(!Objects.isNull(distancePower) && distancePower > 0){
            GeoDistanceQueryBuilder location = QueryBuilders.geoDistanceQuery("data." + CustomerManagementEnum.ADDRESS.getAttr() + ".location")
                    .point(lat,lon)
                    .distance(distancePower,DistanceUnit.METERS);
            boolQueryBuilder.filter(location);
        }
        GeoDistanceSortBuilder sort = SortBuilders.geoDistanceSort("data." + CustomerManagementEnum.ADDRESS.getAttr() + ".location",lat,lon);
        sort.unit(DistanceUnit.METERS);
        sort.order(SortOrder.ASC);
        sort.point(lat,lon);
        sourceBuilder.sort(sort);
        //分页
        Integer page = nearCustomerDTO.getPage();
        Integer pageSize = nearCustomerDTO.getPageSize();
        EsUtil.setPage(sourceBuilder, page, pageSize);
        nearCustomerDTO.setPage(page);
        nearCustomerDTO.setPageSize(pageSize);
        IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, customerIndex.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(customerIndex.getIndex());
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = xbbElasticsearchRestTemplate.search(searchRequest);
        return searchResponse.getHits();
    }

    @Override
    public ListAppVO mobileNearCustomerList(NearCustomerDTO nearCustomerDTO) throws XbbException {
        List<AppListPojo> appListPojos = new ArrayList<>();
        if (!Objects.equals(nearCustomerDTO.getSubBusinessType(),XbbRefTypeEnum.CUSTOMER_NEARBY.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        String corpid = nearCustomerDTO.getCorpid();
        String userId = nearCustomerDTO.getUserId();
        Long formId = nearCustomerDTO.getFormId();
        nearCustomerDTO.setDistancePower(DistanceEnum.getByCode(nearCustomerDTO.getDistance()));
        nearCustomerDTO.setIsArchived(1);

        // 18377 【阁润专项】App附近客户列表页筛选公海客户结果错误。
        try {
            List<ConditionsEntityExt> conditions = nearCustomerDTO.getConditions();
            if (CollectionsUtil.isEmpty(conditions)) {
                conditions = new ArrayList<>();
            }
            JSONArray mobileSpecialFilter = nearCustomerDTO.getMobileSpecialFilter();
            if (CollectionsUtil.isNotEmpty(mobileSpecialFilter)) {
                List<ConditionsEntityExt> conditionsEntityExts = mobileSpecialFilter.toJavaList(ConditionsEntityExt.class);
                conditions.addAll(conditionsEntityExts);
                for (ConditionsEntityExt conditionsEntityExt : conditionsEntityExts) {
                    if (Objects.equals(conditionsEntityExt.getAttr(), "num_3")) {
                        List<Object> values = conditionsEntityExt.getValue();
                        if (values != null && values.size() == 1) {
                            String value = Objects.toString(values.get(0));
                            if (Objects.equals(value, "1")) {
                                nearCustomerDTO.setIsPublic(1);
                                break;
                            }
                        }
                    }
                }
            } else {
                // 附近客户默认是筛选普通客户
                conditions.add(new ConditionsEntityExt(CustomerManagementEnum.IS_PUBLIC.getAttr(), null, CustomerManagementEnum.IS_PUBLIC.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(0)));
            }
            nearCustomerDTO.setConditions(conditions);
        } catch (Exception e) {
            LOG.info(e.getMessage());
        }

        // app端范围筛选
        UserEntity loginUserEntity = new UserEntity();
        BeanUtil.copyProperties(nearCustomerDTO.getLoginUser(),loginUserEntity);
        saasListDataPermissionHelp.dingtalkRangeScreen(nearCustomerDTO.getConditions(), loginUserEntity, nearCustomerDTO.getBusinessType(), nearCustomerDTO.getSubBusinessType(), nearCustomerDTO.getPlatform());

        SearchHits hits = getNearCustomerEsList(nearCustomerDTO);
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        List<Long> customerIdIn = new ArrayList<>();
        List<Long> publicCustomerIdIn = new ArrayList<>();
        List<Long> idIn = new ArrayList<>();
        customerIdIn.add(-1L);
        publicCustomerIdIn.add(-1L);
        idIn.add(-1L);
        //其他列表中的公海客户
        for (SearchHit hit : hits) {
            PaasFormDataEntityExt entity = JSONObject.parseObject(hit.getSourceAsString(),PaasFormDataEntityExt.class);
            JSONObject data = entity.getData();
            idIn.add(entity.getId());
            Integer isPublic = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
            if(1 == isPublic){
                publicCustomerIdIn.add(entity.getId());
            } else {
                customerIdIn.add(entity.getId());
            }
        }
        // 设置前负责人
        Map<Long,String> publicMainUserMap = userTeamService.getMainUserMap(publicCustomerIdIn,corpid,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),true);
        // 设置负责人
        Map<Long,String> mainUserMap = userTeamService.getMainUserMap(customerIdIn,corpid,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),false);

        Map<Long, TagLinkEntity> tagMap = tagLinkModel.getPublicTagLink(corpid, idIn, XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode());

        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
        // TODO 将字段解释传入判断设置电话是否可见
        //Map<Integer, String> customerNamePhoneMap = customerModel.getNamePhoneMap(userEntity, esEntities, corpid, explainList);
        //有提醒的客户
        List<Long> pushNotifyList = new ArrayList<>();
        saasListHelp.getPushNotify(idIn, corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), pushNotifyList);

        boolean isShare;
        try {
            isShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getAlias(), BasicConstant.IS_USE.toString());
        } catch (XbbException e) {
            isShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getValue(), BasicConstant.IS_USE.toString());
        }
        List<Long> dataIdList;
        if (isShare){
            dataIdList = customerFocusModel.getShareCustomerIdList(corpid);
        }else {
            dataIdList = customerFocusModel.getNoShareCustomerIdList(userId,corpid);
        }
        Map<Long, Integer> focusMap = new HashMap<>(dataIdList.size());
        for (Long customerId : dataIdList) {
            focusMap.put(customerId, 1);
        }

        boolean isActiveCall = callCenterCommonService.isOpenCallDingTalk(corpid, userId);
        // TODO long.rao 是否有查看呼叫中心的权限
        for (SearchHit hit : hits) {
            PaasFormDataEntityExt entity = JSONObject.parseObject(hit.getSourceAsString(),PaasFormDataEntityExt.class);
            JSONObject data = entity.getData();
            Long customerId = entity.getDataId();
            String name = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
            Integer isPublic = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
            Integer isAchived = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_ARCHIVED.getAttr(), 0);
            JSONArray explains = new JSONArray();
            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();
            // 解释
            if(Objects.equals(isPublic, 1)){
                //前负责人
                explains.add(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID)+"："+ publicMainUserMap.getOrDefault(customerId, ""));
            }else{
                explains.add(I18nMessageUtil.getMessage(CommonConstant.MAIN_USER)+"：" + mainUserMap.getOrDefault(customerId, ""));
            }
            Double distance = Double.valueOf(hit.getSortValues()[0].toString());
            distance = distance == null ? -1D : distance;
            distance = distance.isInfinite() ? -1D : distance;
            BigDecimal distanceDecimal = BigDecimal.valueOf(distance).setScale(2, RoundingMode.UP);
            distance = distanceDecimal.doubleValue();
            String distanceStr = "";
            if (Objects.equals(distance, -1D)) {
                distanceStr = I18nMessageUtil.getMessage(I18nStringConstant.DISTANCE_NOT_BE_CALCULATED);
            } else if (distance >= 0 && distance < 1000) {
                distanceStr = distance + "m";
            } else if (distance >= 1000) {
                distanceStr = new BigDecimal(distance/1000).setScale(2, RoundingMode.UP).doubleValue() + "km";
            } else {
                distanceStr = I18nMessageUtil.getMessage(I18nStringConstant.DISTANCE_NOT_BE_CALCULATED);
            }

            // 角标 -
            superScript.put("message", pushNotifyList.contains(customerId) ? 1 : 0);
            //非重点客户列表，添加已关注客户标记
            if (null != focusMap.get(customerId)) {
                superScript.put("focus", 1);
            }
            if(Objects.equals(isAchived, 1)){
                superScript.put("archived", 1);
            }
            // 退字标签
            if(tagMap != null && tagMap.containsKey(customerId)){
                superScript.put("back", tagMap.getOrDefault(customerId, new TagLinkEntity()));
            }
            // 其他
            //最后跟进时间
            Long lastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);
            JSONObject lastConnectObj = DateTimeUtil.formatLastConnectTime(lastConnectTime, DateTimeUtil.getInt());
            others.put("lastConnectTime", lastConnectObj.get("lastConnectTimeStr"));
            others.put("lastConnectTimeDay",lastConnectObj.get("lastConnectTimeDay"));
            Double longitude = 0D;
            Double Latitude = 0D;
            if (distance >= 0){
                Latitude = data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()).getJSONObject(FieldTypeEnum.LOCATION.getAlias()).getDouble("lat");
                longitude = data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()).getJSONObject(FieldTypeEnum.LOCATION.getAlias()).getDouble("lon");
                //导航
                others.put("navigate",1);
            }
            others.put("longitude", longitude);
            others.put("latitude", Latitude);
            if(Objects.equals(isPublic, 1)){
                others.put("isGrab",1);
                superScript.put("public",1);
            }
            boolean isShowCallCenterPhone = true;
            boolean isShowCall = isActiveCall && isShowCallCenterPhone;
            if(isShowCall){
                saasListHelp.setCallPhone(userEntity, explainMap, entity, others);
            }
            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            if (titleList.isEmpty()) {
                FormTitlePoJo titlePoJo = new FormTitlePoJo();
                titlePoJo.setValue(Collections.singletonList(name));
                titleList.add(titlePoJo);
            }
            summaryList.add(commonHelp.setSummary(I18nMessageUtil.getMessage(CommonConstant.DISTANCE), distanceStr));
            appListPojos.add(new AppListPojo(customerId, titleList, summaryList, superScript, lablesList, others, entity.getAppId(), entity.getMenuId(), entity.getFormId(), name));
        }
        ListAppVO listAppVO = new ListAppVO();
        listAppVO.setList(appListPojos);
        listAppVO.setTotalCount((int) hits.getTotalHits().value);
        return  listAppVO;
    }

    @Override
    public PaasFormDataEsListVO publicCustomer(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return publicPoolListQry.publicPoolExecute(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO waitProduceList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_PRODUCE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        Integer businessType = formDataListDTO.getBusinessType();
        if (!(Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode()))){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        //获取所有的缺货合同
        formDataListDTO.getConditions().addAll(saasListHelp.packageWaitProduceCondition(formDataListDTO));
        PaasFormEntity paasFormEntity = paasFormModel.getByKey(formDataListDTO.getFormId(),formDataListDTO.getCorpid());
        formDataListDTO.setAppId(paasFormEntity.getAppId());
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO waitPurchaseList(FormDataListDTO formDataListDTO) throws XbbException{
        if (!Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_PURCHASE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        Integer businessType = formDataListDTO.getBusinessType();
        if (!(Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode()))){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        //        formDataListDTO.getConditions().addAll(saasListHelp.packageWaitPurchaseCondition(formDataListDTO));
        //待采购列表有两个分组，一个是展示合同一个展示产品，后台手动置一下appId
        PaasFormEntity paasFormEntity = paasFormModel.getByKey(formDataListDTO.getFormId(),formDataListDTO.getCorpid());
        if(Objects.isNull(paasFormEntity)){
            throw new XbbException(ThirdPartyUsageErrorCodeEnum.API_ERROR_900005);
        }
        formDataListDTO.setAppId(paasFormEntity.getAppId());
        // 待采购可见权限
        UserVO loginUser = formDataListDTO.getLoginUser();
        if (!loginUser.getPermSet().contains(ProPermissionAliasEnum.ORDER_ON_PIN_VIEW.getAlias())){
            throw new XbbException(PurchaseErrorCodeEnum.API_ERROR_225035);
        }
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        if (Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode())){
            //合同维度列表
            formDataListVO = saasListHelp.packageWaitPurchase(formDataListDTO);
        }else if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode())){
            formDataListVO = saasListHelp.packageWaitPurchaseProduct(formDataListDTO);
        }
        return formDataListVO;
    }

    @Override
    public PaasFormDataEsListVO productListSuper(FormDataListDTO formDataListDTO) throws XbbException {
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (!notExport || Objects.equals(PlatFormEnum.DINGTALK.getValue(), formDataListDTO.getPlatform())) {
            //产品列表的筛选条件会作用到父产品或子产品或两者上
            //筛选条件来源：模糊搜索、常用筛选、分组
            String corpid = formDataListDTO.getCorpid();
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(formDataListDTO.getLoginUser(), userEntity);
            List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
            List<List<ConditionsEntityExt>> shouldConditonList = formDataListDTO.getShouldConditions();
            saasListHelp.packageGroupList(formDataListDTO, conditionsEntityExtList, shouldConditonList);
            List<ConditionsEntityExt> parentConditionList = new ArrayList<>();
            List<ConditionsEntityExt> childConditionList = new ArrayList<>();
            Iterator<ConditionsEntityExt> iterator = conditionsEntityExtList.iterator();
            while (iterator.hasNext()) {
                ConditionsEntityExt conditionsEntityExt = iterator.next();
                String attr = conditionsEntityExt.getAttr();
                if (Objects.equals(attr, ProductEnum.CATEGORY_ID.getAttr())) {
                    Long categoryId = Long.valueOf(conditionsEntityExt.getValue().get(0).toString());
                    List<ProductCategoryEntity> productCategoryList = productCategoryService.getSubCategoryIdList(corpid, categoryId);
                    if (Objects.isNull(productCategoryList)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                    List<Long> productCategoryIdIn = new ArrayList<>();
                    productCategoryList.forEach(item -> productCategoryIdIn.add(item.getId()));
                    if (!productCategoryIdIn.isEmpty()) {
                        List<Object> categoryIdIn = new ArrayList<>(productCategoryIdIn);
//                    EsConditionUtil.getConditionList(parentConditionList, ProductEnum.CATEGORY_ID.getAttr(), "",
//                            ProductEnum.CATEGORY_ID.getFieldType(), ConditionEnum.IN.getSymbol(), categoryIdIn);
                        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol()
                        );
                        conditionsEntityExt.setValue(categoryIdIn);
                    }
                }


                boolean isChildField = ChildProductFieldEnum.isChildField(attr);
                boolean isParentField = ParentProductFieldEnum.isParentField(attr);
                if (isChildField && !isParentField) {
                    //子产品字段
                    if (Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())) {
                        conditionsEntityExt.setAttr(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                    }
                    childConditionList.add(conditionsEntityExt);
                    iterator.remove();
                } else if (!isChildField && isParentField) {
                    //父产品字段
                    parentConditionList.add(conditionsEntityExt);
                } else if (isChildField && isParentField) {
                    //共有字段，需要拿出字产品idIn和父产品条件或条件
//                shouldConditonList
                } else {
                    //自定义字段
                    parentConditionList.add(conditionsEntityExt);
                }
                if (Objects.equals(conditionsEntityExt.getFieldType(), FieldTypeEnum.NUM.getType()) && !Objects.equals(conditionsEntityExt.getAttr(), ProductEnum.ONLINE.getAttr())) {
                    ConditionsEntityExt numExistCondition = productNumAttrSearch(conditionsEntityExt);
                    if (Objects.nonNull(numExistCondition)) {
                        if (isChildField && !isParentField) {
                            childConditionList.add(numExistCondition);
                        } else if (!isChildField && isParentField) {
                            //父产品字段
                            parentConditionList.add(numExistCondition);
                        } else if (isChildField && isParentField) {
                        } else {
                            //自定义字段
                            parentConditionList.add(numExistCondition);
                        }
                    }
                }
            }
            String nameLike = formDataListDTO.getNameLike();
            if (!StringUtil.isEmpty(nameLike)) {
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                EsUtil.getTermQuery(boolQueryBuilder, formDataListDTO, true);
                boolQueryBuilder.filter(matchPhraseQuery("data." + ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), nameLike));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.DATA_ID);
                fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID));
                List<PaasFormDataEntityExt> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
                Set<Long> parentIdList = new HashSet<>();
                for (PaasFormDataEntityExt entityExt : childProductList) {
                    parentIdList.add(entityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                }
                formDataListDTO.setNameLikeIdIn(new ArrayList<>(parentIdList));
            }
            if (!childConditionList.isEmpty()) {
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                EsUtil.getTermQuery(boolQueryBuilder, formDataListDTO, true);
                EsUtil.parseCondition(boolQueryBuilder, childConditionList, "", corpid, XbbRefTypeEnum.PRODUCT.getCode());
//            boolQueryBuilder.filter(termQuery(ProductEnum.getEsAttr4Keyword(ProductEnum.PARENT_ID),0));
                List<String> childProductFieldList = new ArrayList<>();
                childProductFieldList.add(StringConstant.DATA_ID);
                childProductFieldList.add(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID));
                List<PaasFormDataEntityExt> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, childProductFieldList);
                Set<Long> parentIdList = new HashSet<>();
                parentIdList.add(-1L);
                for (PaasFormDataEntityExt entityExt : childProductList) {
                    parentIdList.add(entityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                }
                parentConditionList.add(new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(), "", FieldTypeEnum.DATAID.getType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(parentIdList)));
            }
            //默认父产品，首页自定义指标穿透是子产品
            if(formDataListDTO.isThrough()){
                parentConditionList.add(new ConditionsEntityExt(ProductEnum.PARENT_ID.getAttr(), "", ProductEnum.PARENT_ID.getFieldType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(0)));
            }else {
                parentConditionList.add(new ConditionsEntityExt(ProductEnum.PARENT_ID.getAttr(), "", ProductEnum.PARENT_ID.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(0)));
            }
            //分组提前解析，这里重置
            formDataListDTO.setListGroupId(0L);
            formDataListDTO.setDefaultGroup(1);
            formDataListDTO.setConditions(parentConditionList);
            saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditonList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.PRODUCT.getCode(), formDataListDTO.getLoginUser().getDepSet());
            formDataListDTO.setShouldConditions(shouldConditonList);
            return paasFormDataService.listByEs(formDataListDTO);
        }
        AbstractWebDataAnalysisHandle abstractWebDataAnalysisHandle = webDataAnalysisFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        PaasFormDataEsListVO paasFormDataEsListVO = abstractWebDataAnalysisHandle.analysisData(formDataListDTO);
        if (notExport){
            paasFormDataEsListVO.setExplainMap(new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO competitorList(FormDataListDTO formDataListDTO) throws XbbException {
        return commonListQry.execute(formDataListDTO);
    }

    @Override
    public ChildExpansionListVO childProductList(FormDataListDTO formDataListDTO) throws XbbException {
        ChildExpansionListVO json = new ChildExpansionListVO();
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Long parentId = formDataListDTO.getParentId();
        PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, formDataListDTO.getFormId(), businessType);
        Map<String, FieldAttrEntity> productExplainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
        FieldAttrEntity priceField = productExplainMap.get(ProductEnum.PRICE.getAttr());
        FieldAttrEntity costField = productExplainMap.get(ProductEnum.COST.getAttr());
        FieldAttrEntity stockField = productExplainMap.get(ProductEnum.STOCK.getAttr());
        // 查询子产品
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", formDataListDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery("formId", formDataListDTO.getFormId()));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID), parentId));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), FieldTypeEnum.SERIALNO.getAlias(), ProductEnum.getAttrConnectData(ProductEnum.BARCODE), ProductEnum.getAttrConnectData(ProductEnum.COST), ProductEnum.getAttrConnectData(ProductEnum.PRICE),
                ProductEnum.getAttrConnectData(ProductEnum.SPECIFICATION), ProductEnum.getAttrConnectData(ProductEnum.SPECIFICATION_LINK_TEXT), ProductEnum.getAttrConnectData(ProductEnum.STOCK), FieldTypeEnum.CREATORID.getAlias());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        searchRequest.source(sourceBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, formDataListDTO.getPage(), formDataListDTO.getPageSize());
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
        List<PaasFormDataEntityExt> childProductList = esEntities.getContent();
        long num = esEntities.getTotalElements();
        PageHelper pageHelper = new PageHelper(formDataListDTO.getPage(), formDataListDTO.getPageSize());
        pageHelper.setRowsCount((int) num);
        json.setPageHelper(pageHelper);
        //List<PaasFormDataEntityExt> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        if (childProductList.isEmpty()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        List<Long> childIdList = new ArrayList<>(childProductList.size());
        childProductList.forEach(item -> childIdList.add(item.getDataId()));
        boolean enableMultiUnit = childProductList.get(0).getData().getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()) == 1 ? true : false;
        Map<Long, List<PaasFormDataEntityExt>> multiProductsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (enableMultiUnit) {
            ProductFieldPojo productFieldPojo = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_UNIT, ProductEnum.UNIT.getAttr(), corpid);
            Map<Long, List<UnitItemPoJo>> groupMap = productFieldPojo.getMultiItems().stream().collect(Collectors.toMap(MultiUnitItemPoJo::getValue, MultiUnitItemPoJo::getItemDataPoJoList));
            List<ProductUnitPriceEntity> entitys = productUnitPriceModel.getPriceEntitysByParentId(corpid, parentId);
            for (ProductUnitPriceEntity entity : entitys) {
                List<PaasFormDataEntityExt> multiProductList = new ArrayList<>();
                JSONArray price = entity.getPrice();
                List<UnitItemPoJo> unitItemPoJos = groupMap.get(entity.getUnitGroupId());
                if (unitItemPoJos.size() != price.size()){
                    price = productService.formatMultiPrice(unitItemPoJos, price);
                }
                for (int i = 0; i < price.size(); i++) {
                    JSONObject child = (JSONObject) price.get(i);
                    child.put(ProductEnum.PRICE.getAttr(), child.getDoubleValue(BasicConstant.RATE));
                    PaasFormDataEntityExt entityExt = new PaasFormDataEntityExt();
                    entityExt.setData(child);
                    multiProductList.add(entityExt);
                }
                multiProductsMap.put(entity.getProductId(), multiProductList);
            }
        }
        //拿到打促销的子产品
        HashSet<Long> discountChildSet = marketingHelp.getChildPromotionProduct(parentId, corpid);
        Map<Long, List<ProductWarehouseEntity>> productWarehouseMap =  productWarehouseModel.getWarehouseProductMap(formDataListDTO.getCorpid(), childIdList, Arrays.asList(ProductWarehouseSubFormEnum.getAttrConnectDataByDbAttr(StringConstant.PARENTID), ProductWarehouseSubFormEnum.getAttrConnectDataByDbAttr(ParameterConstant.WAREHOUSE_ID), ProductWarehouseSubFormEnum.getAttrConnectDataByDbAttr("productId"), ProductWarehouseSubFormEnum.getAttrConnectDataByDbAttr("cost"), ProductWarehouseSubFormEnum.getAttrConnectDataByDbAttr("num")));
        productService.formatChildSpecification(childProductList, corpid);
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserIdMap(Collections.singletonList(parentId),corpid,businessType,false,mainUserMap,coUserMap);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO);
        handlerExplainDTO.setOwnerId(mainUserMap.get(parentId));
        handlerExplainDTO.setCoUserId(coUserMap.get(parentId));
        handlerExplainDTO.setCreatorId(childProductList.get(0).getCreatorId());
        boolean isPriceHide = ExplainUtil.isFieldNeedHide(priceField, handlerExplainDTO);
        boolean isCostHide = ExplainUtil.isFieldNeedHide(costField, handlerExplainDTO);
        boolean isStockHide = ExplainUtil.isFieldNeedHide(stockField, handlerExplainDTO);
        JSONArray childProductArray = new JSONArray();
        List<SubOptionTableHeadEnum> optionTableHeadEnums = new ArrayList<>(OptionTableHeadEnum.getListByBusinessType(businessType));
        childProductList.forEach(item -> {
            JSONObject childObject = new JSONObject();
            if (!isPriceHide && Objects.equals(priceField.getIsOpen(), 1)) {
                childObject.put(ProductEnum.PRICE.getSaasAttr(), item.getData().get(ProductEnum.PRICE.getAttr()));
                //多单位产品都需要做价格排序
                if (enableMultiUnit) {
                    try {
                        String priceOrCostRegion = productService.getPriceOrCostRegion(multiProductsMap.getOrDefault(item.getDataId(), new ArrayList<>()), ProductEnum.PRICE.getAttr(), null);
                        childObject.put(ProductEnum.PRICE.getSaasAttr(), priceOrCostRegion);
                    } catch (XbbException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (!isCostHide && Objects.equals(costField.getIsOpen(), 1)) {
                childObject.put(ProductEnum.COST.getSaasAttr(), item.getData().get(ProductEnum.COST.getAttr()));
            }
            if (!isStockHide && Objects.equals(stockField.getIsOpen(), 1)) {
                if (productWarehouseMap.containsKey(item.getDataId())) {
                    Double allStock = 0D;
                    for (ProductWarehouseEntity productWarehouseEntity : productWarehouseMap.get(item.getDataId())) {
                        if (!Objects.equals(productWarehouseEntity.getWarehouseId(), 0L)) {
                            allStock = Arith.add(allStock, productWarehouseEntity.getNum());
                        }
                    }
                    childObject.put(ProductEnum.STOCK.getSaasAttr(), allStock);
                } else {
                    childObject.put(ProductEnum.STOCK.getSaasAttr(), 0D);
                }
            }
            childObject.put(ProductEnum.BARCODE.getSaasAttr(), item.getData().get(ProductEnum.BARCODE.getAttr()));
            childObject.put(ProductEnum.PRODUCT_NO.getSaasAttr(), item.getData().get(ProductEnum.PRODUCT_NO.getAttr()));
            childObject.put(ProductEnum.SPECIFICATION.getSaasAttr(), item.getData().get(ProductEnum.SPECIFICATION.getAttr()));
            JSONArray jsonArray = JSON.parseArray(item.getData().getString(ProductEnum.PRODUCT_IMGS.getAttr()));
            childObject.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), jsonArray != null ? jsonArray : new JSONArray());
            childObject.put(SelectProductEnum.DISCOUNT.getSaasAttr(), BasicConstant.ZERO);
            if (discountChildSet.contains(item.getDataId())) {
                childObject.put(SelectProductEnum.DISCOUNT.getSaasAttr(), BasicConstant.ONE);
            }
            childProductArray.add(childObject);
        });
        json.setValue(childProductArray);
        JSONArray tableHead = new JSONArray();
        optionTableHeadEnums.forEach(item -> {
            JSONObject table = new JSONObject();
            table.put(StringConstant.PROP, item.getProp());
            table.put(StringConstant.LABEL, item.getLabel());
            tableHead.add(table);
        });
        json.setTableHead(tableHead);
        return json;
    }

    private ConditionsEntityExt productNumAttrSearch(ConditionsEntityExt conditionsEntityExt) {
        String attr = conditionsEntityExt.getAttr();
        String subAttr =  conditionsEntityExt.getSubAttr();

        Integer fieldType = conditionsEntityExt.getFieldType();
        ConditionsEntityExt numExistCondition = null;
        ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(conditionsEntityExt.getSymbol());
        switch (conditionEnum){
            case EQUAL:
                if (Objects.equals(conditionsEntityExt.getValue().get(0).toString(),"0")){
                    numExistCondition = new ConditionsEntityExt(attr,subAttr,fieldType,ConditionEnum.EMPTY.getSymbol(),new ArrayList<>());
                }
                break;
            case NOEQUAL:
                if (Objects.equals(conditionsEntityExt.getValue().get(0).toString(),"0")){
                    numExistCondition = new ConditionsEntityExt(attr,subAttr,fieldType,ConditionEnum.NOEMPTY.getSymbol(),new ArrayList<>());
                }
                break;
            case GREATEREQUAL:
                if (Long.valueOf(conditionsEntityExt.getValue().get(0).toString()) <= 0L){
                    numExistCondition = new ConditionsEntityExt(attr,subAttr,fieldType,ConditionEnum.EMPTY.getSymbol(),new ArrayList<>());
                }
                break;
            case GREATERTHAN:
                if (Long.valueOf(conditionsEntityExt.getValue().get(0).toString()) < 0L){
                    numExistCondition = new ConditionsEntityExt(attr,subAttr,fieldType,ConditionEnum.EMPTY.getSymbol(),new ArrayList<>());
                }
                break;
            case LESSEQUAL:
                if (Long.valueOf(conditionsEntityExt.getValue().get(0).toString()) >= 0L){
                    numExistCondition = new ConditionsEntityExt(attr,subAttr,fieldType,ConditionEnum.EMPTY.getSymbol(),new ArrayList<>());
                }
                break;
            case LESSTHAN:
                if (Long.valueOf(conditionsEntityExt.getValue().get(0).toString()) > 0L){
                    numExistCondition = new ConditionsEntityExt(attr,subAttr,fieldType,ConditionEnum.EMPTY.getSymbol(),new ArrayList<>());
                }
                break;
            case RANGE:
                if ((Objects.isNull(conditionsEntityExt.getValue().get(0)) || conditionsEntityExt.getValue().get(0).toString().isEmpty())
                        || (Objects.isNull(conditionsEntityExt.getValue().get(1)) || conditionsEntityExt.getValue().get(1).toString().isEmpty())){
                    // 如果查询参数的值为空，则不处理这个，防止报错
                    break;
                }
                if (Long.valueOf(conditionsEntityExt.getValue().get(0).toString()) * Long.valueOf(conditionsEntityExt.getValue().get(1).toString()) <= 0L){
                    numExistCondition = new ConditionsEntityExt(attr,subAttr,fieldType,ConditionEnum.EMPTY.getSymbol(),new ArrayList<>());
                }
                break;
            default:
                break;
        }
        return numExistCondition;
    }

    /**
     * 列表状态筛选
     * @param formDataListDTO 参数
     * @param attr 字段
     */
    @Override
    public void setStatusFilter(FormDataListDTO formDataListDTO, String attr) {
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        if (conditionList == null){
            conditionList = new ArrayList<>();
        }
        if (formDataListDTO.getStatusFilter() != null && formDataListDTO.getStatusFilter() != 0){
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(attr);
            conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt.setValue(Collections.singletonList(formDataListDTO.getStatusFilter()));
            conditionList.add(conditionsEntityExt);
        }
        formDataListDTO.setConditions(conditionList);
    }

    @Override
    public PaasFormDataEsListVO supplierContactList(FormDataListDTO formDataListDTO) throws XbbException{
        Integer businessType = formDataListDTO.getBusinessType();
        if (!Objects.equals(businessType,XbbRefTypeEnum.SUPPLIER_CONTACT.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        formDataListDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode());
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO warehouseList(FormDataListDTO formDataListDTO) throws XbbException {
        Integer businessType = formDataListDTO.getBusinessType();
        if (!Objects.equals(businessType,XbbRefTypeEnum.WAREHOUSE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        formDataListDTO.setBusinessType(XbbRefTypeEnum.WAREHOUSE.getCode());
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<List<ConditionsEntityExt>> shouldConditions = formDataListDTO.getShouldConditions();
        saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditions,formDataListDTO.getLoginUser(),XbbRefTypeEnum.WAREHOUSE.getCode(),formDataListDTO.getLoginUser().getDepSet());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(formDataListDTO.getConditions(),userEntity,XbbRefTypeEnum.WAREHOUSE.getCode(),formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setShouldConditions(shouldConditions);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO refundList(FormDataListDTO formDataListDTO) throws XbbException{
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.REFUND.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return commonListQry.execute(formDataListDTO);
//        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
//        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
//        UserEntity userEntity = new UserEntity();
//        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.REFUND.getCode(), formDataListDTO.getSubBusinessType());
//        // app端筛选筛选
//        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.REFUND.getCode(),formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
//        formDataListDTO.setConditions(conditionList);
//        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO returnList(FormDataListDTO formDataListDTO) throws XbbException{
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.REFUND.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.REFUND.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.REFUND.getCode(),formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }
    @Override
    public PaasFormDataEsListVO quotationList(FormDataListDTO formDataListDTO) throws XbbException{
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.QUOTATION.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
//        setStatusFilter(formDataListDTO, QuotationEnum.ARCHIVED.getAttr());
//        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
//        //判断conditionList中是否存在 is_new字段，自定义指标需要查询历史版本数据
//        boolean isNewExist = false;
//        for (ConditionsEntityExt e : conditionList) {
//            if (Objects.equals(QuotationEnum.IS_NEW.getAttr(), e.getAttr()) && Objects.equals(XbbRefTypeEnum.QUOTATION.getCode(), formDataListDTO.getSubBusinessType())) {
//                isNewExist = true;
//            }
//        }
//        if(!isNewExist){
//            conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
//        }
//        UserEntity userEntity = new UserEntity();
//        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
//        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.QUOTATION.getCode(), formDataListDTO.getSubBusinessType());
//        // app端范围筛选
//        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.QUOTATION.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
//        formDataListDTO.setConditions(conditionList);
//        return paasFormDataService.listByEs(formDataListDTO);
        return commonListQry.execute(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO paymentSheetList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(formDataListDTO.isThrough(), conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.PAYMENT_SHEET.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);

        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.PAYMENT_SHEET.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        //处理坏账回款单需要的划横线
        List<FieldAttrEntity> headList = paasFormDataEsListVO.getHeadList();
        for (FieldAttrEntity fieldAttrEntity : headList) {
            if(Objects.equals(fieldAttrEntity.getAttr(), PaymentSheetEnum.AMOUNT.getAttr())){
                fieldAttrEntity.setBadFlag(BasicConstant.ONE);
            }
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO onlinePaymentFlowList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        /*
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        */
        saasListDataPermissionHelp.listDataPermission(formDataListDTO.isThrough(), conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getCode(), formDataListDTO.getSubBusinessType());
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO paySheetList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.PAY_SHEET.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.PAYMENT_SHEET.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        //处理坏账回款单需要的划横线
        List<FieldAttrEntity> headList = paasFormDataEsListVO.getHeadList();
        for (FieldAttrEntity fieldAttrEntity : headList) {
            if(Objects.equals(fieldAttrEntity.getAttr(), PaySheetEnum.AMOUNT.getAttr())){
                fieldAttrEntity.setBadFlag(BasicConstant.ONE);
            }
        }
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO otherIncomeList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.OTHER_INCOME.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        List<ConditionsEntityExt> conditionsEntityExts = saasListDataPermissionHelp.listDataPermission(formDataListDTO.isThrough(), conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.OTHER_INCOME.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(conditionsEntityExts, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        conditionList.addAll(conditionsEntityExts);
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.OTHER_INCOME.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO otherExpenseList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.OTHER_EXPENSE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        List<ConditionsEntityExt> conditionsEntityExts = saasListDataPermissionHelp.listDataPermission(formDataListDTO.isThrough(), conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.OTHER_EXPENSE.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(conditionsEntityExts, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.OTHER_EXPENSE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        return paasFormDataEsListVO;
    }

    /**
     * 资金调拨单列表
     *
     * @param formDataListDTO
     * @return
     * @throws XbbException
     */
    @Override
    public PaasFormDataEsListVO fundTransferList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.FUND_TRANSFER.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        List<ConditionsEntityExt> conditionsEntityExts = saasListDataPermissionHelp.listDataPermission(formDataListDTO.isThrough(), conditionList, formDataListDTO.getLoginUser(), XbbRefTypeEnum.FUND_TRANSFER.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(conditionsEntityExts, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList, userEntity, XbbRefTypeEnum.FUND_TRANSFER.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
        return paasFormDataEsListVO;
    }

    @Override
    public boolean getAppListAddPermission(Object paasFormDataEsListVO) {
        try {
            if (Objects.isNull(paasFormDataEsListVO)) {
                return false;
            }
            List<ButtonPojo> buttonPojoList = null;
            if (paasFormDataEsListVO instanceof PaasFormDataEsListVO) {
                buttonPojoList = ((PaasFormDataEsListVO) paasFormDataEsListVO).getTopPermissions();
            } else if (paasFormDataEsListVO instanceof WorkReportVO) {
                buttonPojoList = ((WorkReportVO) paasFormDataEsListVO).getTopPermissions();
            } else if (paasFormDataEsListVO instanceof WorkOrderDataEsListVO) {
                buttonPojoList = ((WorkOrderDataEsListVO) paasFormDataEsListVO).getTopPermissions();
            }
            if (Objects.nonNull(buttonPojoList) && !buttonPojoList.isEmpty()) {
                for (ButtonPojo buttonPojo : buttonPojoList) {
                    if (Objects.nonNull(buttonPojo) && Objects.equals(buttonPojo.getAttr(), SaasButtonEnum.ADD.getAttr())) {
                        return true;
                    }
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public ListAppVO appList(FormDataListDTO formDataListDTO) throws XbbException {
        String platform = formDataListDTO.getPlatform();
        if (!Objects.equals(platform, PlatFormEnum.DINGTALK.getValue())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
        formDataListDTO.setAnalysisAmountOfThousandBitsWithOriginalValue(true);
        PaasFormDataEsListVO formDataListVO = null;
        List<PaasFormDataEntityExt> paasFormDataESList;
        List<AppListPojo> appItemList = new ArrayList<>();
        Integer totalCount = 0;
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getSubBusinessType();
        if (businessType == null) {
            throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        List<Long> dataIds = new ArrayList<>();
        dataIds.add(0L);
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        List<FieldAttrEntity> headList;
        switch (redundantTemplateTypeEnum) {
            case SUPPLIER:
                formDataListVO = supplierList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt entity : paasFormDataESList) {
                    JSONObject formData = entity.getData();
                    String titleShow = FastJsonHelper.getStringOrDefaultFromFormData(formData, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                    //字段解释
                    //其他（右上角，右下角等特殊位置）
                    JSONObject others = new JSONObject();
                    //特殊标签
                    String communicateTimeInterval = I18nMessageUtil.getMessage(StringConstant.NEVER_CONNECT);
                    EsDataDTO esDataDTO = new EsDataDTO();
                    esDataDTO.setCorpid(corpid);
                    esDataDTO.setDel(0);
                    esDataDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode());
                    esDataDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    esDataDTO.setFieldList(null);
                    esDataDTO.setPage(1);
                    esDataDTO.setPageSize(1);
                    Map<String, String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    sortMap.put(SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr(), StringConstant.SORT_DESC_TAG);
                    esDataDTO.setSortMap(sortMap);
                    List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    conditionsEntityExtList.add(EsUtil.packageContions(SupplierCommunicateEnum.SUPPLIER_ID.getAttr(),
                            Collections.singletonList(entity.getDataId()), ConditionEnum.EQUAL, SupplierCommunicateEnum.SUPPLIER_ID.getFieldType()));
                    esDataDTO.setConditionsEntityExtList(conditionsEntityExtList);
                    PaasFormDataEsListVO esDataList = paasFormDataService.getEsDataList(esDataDTO);
                    List<PaasFormDataEntityExt> supplierCommunicateESList = esDataList.getPaasFormDataESList();

                    if (supplierCommunicateESList != null && !supplierCommunicateESList.isEmpty()) {
                        JSONObject supplierCommunicateData = supplierCommunicateESList.get(0).getData();
                        Long communicateTime = FastJsonHelper.getLongOrDefaultFromFormData(supplierCommunicateData, SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr(), 0L);
                        communicateTimeInterval = DateTimeUtil.getLastConnectTimeStr(communicateTime);
                    }
                    others.put("communicateTime", communicateTimeInterval);

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(titleShow));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(entity.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case PURCHASE:
                formDataListVO = purchaseList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    String titleShow = FastJsonHelper.getStringOrDefaultFromFormData(formData, PurchaseEnum.SHEET_NO.getAttr(), "");
                    JSONObject others = new JSONObject();

                    String totalAmount = FastJsonHelper.getStringOrDefaultFromFormData(formData, ContractEnum.AMOUNT.getAttr(), "");
                    if (!StringUtil.isEmpty(totalAmount)) {
                        totalAmount += UnitEnum.MONEY.getName();
                    }
                    others.put(ContractEnum.AMOUNT.getSaasAttr(), totalAmount);

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(titleShow));
                        titleList.add(titlePoJo);
                    }

                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case RETURNED_PURCHASE:
                formDataListVO = returnedPurchaseList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    String titleShow = FastJsonHelper.getStringOrDefaultFromFormData(formData, ReturnedPurchaseEnum.SHEET_NO.getAttr(), "");
                    JSONObject others = new JSONObject();
                    String totalMoney = FastJsonHelper.getStringOrDefaultFromFormData(formData, ReturnedPurchaseEnum.TOTAL_MONEY.getAttr(), "0.0");
                    others.put(ReturnedPurchaseEnum.TOTAL_MONEY.getSaasAttr(), totalMoney + UnitEnum.MONEY.getName());

                    String outStockId = FastJsonHelper.getStringOrDefaultFromFormData(formData, ReturnedPurchaseEnum.OUTSTOCK_ID.getAttr(), "");
                    String outStockStatus = StringUtil.isEmpty(outStockId) ? ReturnedPurchaseStatusEnum.WAIT_OUTSTOCK.getMemo() : ReturnedPurchaseStatusEnum.OUTSTOCK.getMemo();
                    others.put(StringConstant.STATUS, outStockStatus);

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(titleShow));
                        titleList.add(titlePoJo);
                    }

                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                formDataListVO = statement(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    JSONObject formData = paasFormDataEntityExt.getData();
                    JSONObject others = new JSONObject();
                    if (Objects.equals(formDataListDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                        others.put(StringConstant.STATUS, formData.getString(CustomerStatementStatisticDistributorEnum.STATUS.getAttr()));
                    }
                    List<SummaryDataPoJo> summaryList = new ArrayList<>();
                    JSONObject customerInfo = (JSONObject) formData.getJSONArray(CustomerStatementStatisticEnum.CUSTOMER_ID.getAttr()).get(0);
                    SummaryDataPoJo customer = new SummaryDataPoJo(CustomerStatementStatisticEnum.CUSTOMER_ID.getAttr(), CustomerStatementStatisticEnum.CUSTOMER_ID.getAttrName(), CustomerStatementStatisticEnum.CUSTOMER_ID.getFieldType(), Collections.singletonList(customerInfo.getString("name")));
                    if (Objects.equals(formDataListDTO.getDistributorMark(), 1)) {
                        customer = new SummaryDataPoJo(CustomerStatementStatisticDistributorEnum.CUSTOMER_ID.getAttr(), CustomerStatementStatisticDistributorEnum.CUSTOMER_ID.getAttrName(), CustomerStatementStatisticDistributorEnum.CUSTOMER_ID.getFieldType(), Collections.singletonList(customerInfo.getString("name")));
                    }
                    summaryList.add(customer);
                    SummaryDataPoJo checkDate = new SummaryDataPoJo(CustomerStatementStatisticEnum.CHECK_DATE.getAttr(), CustomerStatementStatisticEnum.CHECK_DATE.getAttrName(), CustomerStatementStatisticEnum.CHECK_DATE.getFieldType(), Collections.singletonList(formData.getString(CustomerStatementStatisticEnum.CHECK_DATE.getAttr())));
                    summaryList.add(checkDate);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formData.getString(CustomerStatementStatisticEnum.STATEMENT_NO.getAttr())));
                        titleList.add(titlePoJo);
                    }
                    JSONObject superScript = new JSONObject();
                    if(Objects.equals(paasFormDataEntityExt.getTagData().getInteger("isAchived"), 1)){
                        superScript.put("archived", 1);
                    }
                    appItemList.add(new AppListPojo(paasFormDataEntityExt.getDataId(), titleList, summaryList, superScript, new ArrayList<>(), others));
                }
                break;
            case BOMBILL:
                formDataListVO = bombillList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    String titleShow = FastJsonHelper.getStringOrDefaultFromFormData(formData, BomBillEnum.SHEET_NO.getAttr(), "");
                    JSONObject others = new JSONObject();
                    String status = ItemUtil.parseItemPoJoFromFormData2String(formData, BomBillEnum.STATUS.getAttr(), "");
                    others.put(StringConstant.STATUS, status);

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(titleShow));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case PRODUCTIONORDER:
                formDataListVO = productionOrderList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();

                    Long now = DateTimeUtil.getTodayInt();
                    Long completeTime = FastJsonHelper.getLongOrDefaultFromFormData(formData, ProductionOrderEnum.COMPLETE_TIME.getAttr(), 0L);
                    Long closeTime = FastJsonHelper.getLongOrDefaultFromFormData(formData, ProductionOrderEnum.CLOSE_TIME.getAttr(), 0L);
                    Long planTime = FastJsonHelper.getLongOrDefaultFromFormData(formData, ProductionOrderEnum.PLAN_TIME.getAttr(), 0L);
                    String status4Show = FastJsonHelper.getStringOrDefaultFromFormData(formData, ProductionOrderEnum.STATUS.getAttr(), "");
                    ProductionOrderStatusEnum statusEnum = ProductionOrderStatusEnum.getByAlias(status4Show);
                    boolean overdue = (Objects.equals(statusEnum, ProductionOrderStatusEnum.UNFINISHED) && now > planTime && planTime != 0L)
                            || (Objects.equals(statusEnum, ProductionOrderStatusEnum.FINISHED) && completeTime > planTime && completeTime != 0L)
                            || (Objects.equals(statusEnum, ProductionOrderStatusEnum.CLOSED) && closeTime > planTime && closeTime != 0L);
                    if (overdue) {
                        others.put("color", "red");
                    }

                    String status = ItemUtil.parseItemPoJoFromFormData2String(formData, ProductionOrderEnum.STATUS.getAttr(), "");
                    others.put(StringConstant.STATUS, status);

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case ASSEMBLE:
                formDataListVO = assembleList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();
                    Integer flowStatus = formDataItem.getFlowStatus();
                    // 装配单自动生成出入库单
                    String status = I18nMessageUtil.getMessage(I18nStringConstant.TO_BE_IN_OUT);
                    if (Objects.equals(flowStatus, FlowStatusEnum.NOT_NEED_APPROVAL.getType()) || Objects.equals(flowStatus, FlowStatusEnum.PASS.getType())) {
                        status = I18nMessageUtil.getMessage(I18nStringConstant.IN_OUT);
                    }
                    others.put(StringConstant.STATUS, status);

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case REFUND_INSTOCK:
                formDataListVO = instockList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                /*explainMap = formDataListVO.getExplainMap();
                explainAttrList = getAppListSummaryAttr(businessType);*/
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    //String titleShow = FastJsonHelper.getStringOrDefaultFromFormData(formData, InstockEnum.SHEET_NO.getAttr(), "");
                    //JSONArray explains = new JSONArray();
                    JSONObject others = new JSONObject();
                    if (Objects.equals(businessType,XbbRefTypeEnum.OTHER_INSTOCK.getCode())){
                        //只有其他入库需要这个
                        String type = ItemUtil.parseItemPoJoFromFormData2String(formData, InstockEnum.TYPE.getAttr(), "");
                        others.put(StringConstant.STATUS, type);
                    }else {
                        others.put(StringConstant.STATUS, "");
                    }


                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                formDataListVO = outstockList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();
                    if (Objects.equals(businessType,XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())){
                        String type = ItemUtil.parseItemPoJoFromFormData2String(formData, OutstockEnum.TYPE.getAttr(), "");
                        others.put(StringConstant.STATUS, type);
                    }else {
                        others.put(StringConstant.STATUS, "");
                    }

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case INVENTORY:
                formDataListVO = inventoryList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();

                    others.put(StringConstant.STATUS, ItemUtil.parseItemPoJoFromFormData2String(formData, InventoryEnum.STATUS.getAttr(), ""));

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case TRANSFER:
                formDataListVO = transferList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();
                    others.put(StringConstant.STATUS, ItemUtil.parseItemPoJoFromFormData2String(formData, TransferEnum.STATUS.getAttr(), ""));

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case PAY_PLAN:
                formDataListVO = payPlanList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();
                    String status = commonHelp.formatFundStatusText(formData, PayPlanEnum.PAY_TYPE.getAttr(),"");
                    others.put(StringConstant.STATUS, status);

                    String payAmount = FastJsonHelper.getStringOrDefaultFromFormData(formData, PayPlanEnum.AMOUNT.getAttr(), "0.0");
                    Integer isBad = 0;
                    if ( Objects.equals(PayPlanStatusEnum.getByAlias(status),PayPlanStatusEnum.BAD_DEBT)
                            || Objects.equals(PayPlanStatusEnum.getByAlias(status),PayPlanStatusEnum.PARTIAL_BAD_DEBT)){
                        isBad = 1;
                    }
                    payAmount = payAmount + UnitEnum.MONEY.getName();
                    commonHelp.setPaymentOthers(others, payAmount, status, null,isBad);

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if ( Objects.equals(status, PayPlanStatusEnum.UN_RECEIVABLES.getAlias()) || Objects.equals(status, PayPlanStatusEnum.PARTIAL_RECEIPTS.getAlias()) ) {
                        for ( SummaryDataPoJo summaryDataPoJo : summaryList ) {
                            String attr = summaryDataPoJo.getAttr();
                            if ( Objects.equals(attr, PayPlanEnum.ESTIMATE_TIME.getAttr()) ) {
                                List<Object> valueList = summaryDataPoJo.getValue();
                                if ( valueList.isEmpty() ) {
                                    break;
                                }
                                String valueKey = (String) valueList.get(0);
                                Long estimate = DateTimeUtil.getInt(valueKey, DateTimeUtil.SDFDate);
                                if ( estimate < DateTimeUtil.getTodayInt() ) {
                                    summaryDataPoJo.setStatus("delay");
                                }
                                break;
                            }
                        }
                    }
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case SUPPLIER_CONTACT:
                formDataListVO = supplierContactList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        String name = FastJsonHelper.getStringOrDefaultFromFormData(formData, SupplierContactEnum.NAME.getAttr(), "");
                        titlePoJo.setValue(Collections.singletonList(name));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case WAREHOUSE:
                formDataListVO = warehouseList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();

                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        String name = FastJsonHelper.getStringOrDefaultFromFormData(formData, WarehouseEnum.WAREHOUSE_NAME.getAttr(), "");
                        titlePoJo.setValue(Collections.singletonList(name));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, new JSONObject()));
                }
                break;
            case PRODUCT:
                UserEntity userEntity = new UserEntity();
                BeanUtil.copyProperties(formDataListDTO.getLoginUser(), userEntity);
                saasListDataPermissionHelp.
                        dingtalkRangeScreen(formDataListDTO.getConditions(), userEntity, businessType, null, PlatFormEnum.DINGTALK.getValue());
                setSpecialSearchAttr(formDataListDTO);
                formDataListVO = productListSuper(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                Map<String, FieldAttrEntity> productExplainMap = formDataListVO.getExplainMap();
                FieldAttrEntity stockFieldAttrEntity = productExplainMap.get(SelectProductEnum.STOCK.getAttr());
                HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                handlerExplainDTO.setLoginUser(formDataListDTO.getLoginUser());
                handlerExplainDTO.setUserId(formDataListDTO.getUserId());
                Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
                HashSet<Long> promotionProduct = marketingHelp.getPromotionProduct(corpid);
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();
                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lableList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);

                    String unit = FastJsonHelper.getStringOrDefaultFromFormData(formData, ProductEnum.UNIT.getAttr(), "");
                    others.put(ProductEnum.UNIT.getSaasAttr(), unit);
                    handlerExplainDTO.setCreatorId(formDataItem.getCreatorId());
                    handlerExplainDTO.setOwnerId(Arrays.asList(formDataItem.getOwnerId()));
                    if (!ExplainUtil.isFieldNeedHide(stockFieldAttrEntity,handlerExplainDTO) && Objects.equals(stockFieldAttrEntity.getIsOpen(), 1)) {
                        Double stock = getDoubleOrDefaultFromFormData(formData, ProductEnum.STOCK.getAttr(), 0D);
                        others.put(ProductEnum.STOCK.getSaasAttr(), attrDecimalPrecisionHelper.formatPrecisionWithIntegerOnly(stock, stockFieldAttrEntity) + unit);
//                        others.put(ProductConstant.TRANSFORM_UNIT_RATE, groupItemsMap.get(formData.getLong(ProductEnum.UNIT.getSaasAttr())));
                        formData.remove(ProductEnum.UNIT.getSaasAttr());
                    }else {
                        summaryList.removeIf(item -> Objects.equals(item.getAttr(),ProductEnum.STOCK.getAttr()));
                    }
                    others.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, ProductEnum.PRODUCT_IMGS.getAttr(), new JSONArray()));
                    Integer discount = 0 ;
                    if (promotionProduct.contains(formDataItem.getDataId())) {
                        discount = 1;
                    }
                    appItemList.add(new AppListPojo(discount,formDataItem.getDataId(), titleList, summaryList, null, lableList, others));
                }
                break;
            case COMPETITOR:
                UserEntity user = new UserEntity();
                BeanUtil.copyProperties(formDataListDTO.getLoginUser(),user);
                saasListDataPermissionHelp.
                        dingtalkRangeScreen(formDataListDTO.getConditions(), user, businessType, null, PlatFormEnum.DINGTALK.getValue());
                formDataListVO = competitorList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();

                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    JSONObject data = paasFormDataEntityExt.getData();
                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lableList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);

                    appItemList.add(new AppListPojo(paasFormDataEntityExt.getDataId(),titleList,summaryList,null,lableList,new JSONObject()));
                }
                break;
            case STOCK_SEARCH:
                Long groupId = formDataListDTO.getListGroupId() == null ? ListGroupEnum.PRODUCT_SEARCH.getCode() : formDataListDTO.getListGroupId();
                if (!Objects.equals(groupId, Long.valueOf(ListGroupEnum.PRODUCT_SEARCH.getCode())) && !Objects.equals(groupId, Long.valueOf(ListGroupEnum.WARNING_SEARCH.getCode()))
                        && !Objects.equals(ListGroupEnum.getByCode(groupId.intValue()).getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
                }
                setSpecialSearchAttr(formDataListDTO);
                //处理创建人筛选
                saasListDataPermissionHelp.dingtalkRangeScreen(formDataListDTO.getConditions(),formDataListDTO.getLoginUser(),businessType,formDataListDTO.getSubBusinessType(),platform);
                //saasListDataPermissionHelp.removeByPermission(formDataListDTO.getConditions(),formDataListDTO.getLoginUser(),SaasListDataPermissionHelp.getAppRangeAttrList(businessType));
                formDataListVO = newProductStockList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                FieldAttrEntity warehouseField = null;
                FieldAttrEntity batchFieldAttr = null;
                FieldAttrEntity stockFieldAttr = null;
                FieldAttrEntity guaranteeSearchFieldAttr = null;
                for (FieldAttrEntity fieldAttrEntity : formDataListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), SelectProductEnum.BATCH.getSaasAttr())) {
                        batchFieldAttr = fieldAttrEntity;
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), SelectProductEnum.WAREHOUSE.getSaasAttr())) {
                        warehouseField = fieldAttrEntity;
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), SelectProductEnum.STOCK.getSaasAttr())) {
                        stockFieldAttr = fieldAttrEntity;
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), ListOptionEnum.GUARANTEE_SEARCH.getAttr())) {
                        guaranteeSearchFieldAttr = fieldAttrEntity;
                    }
                }
                Long dataId = 0L;
                //获取产品Id集合
                Map<Long, ContractProductEntity> contractProductEntityMap = new HashMap<>();
                if (!paasFormDataESList.isEmpty()) {
                    List<Long> productIdList = new ArrayList<>();
                    for (PaasFormDataEntityExt entity : paasFormDataESList) {
                        productIdList.add(entity.getId());
                    }
                    //获取产品的待出库数量
                    List<ContractProductEntity> waitOutProductEntitys = contractProductService.getWaitOutstockProductByProductIdIn(productIdList, corpid);
                    if (CollectionsUtil.isNotEmpty(waitOutProductEntitys)) {
                        for (ContractProductEntity contractProductEntity : waitOutProductEntitys) {
                            contractProductEntityMap.put(contractProductEntity.getProductId(), contractProductEntity);
                        }
                    }
                }
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    // 预警查询和保质期查询展示的子产品。但是点击产品跳转详情时需要传父产品id
                    dataId = formDataItem.getParentId() == null ? formDataItem.getDataId() : formDataItem.getParentId();
                    JSONObject others = new JSONObject();
                    List<List<SummaryDataPoJo>> batctList = new ArrayList<>();
                    // 批次保质期信息
                    List<SummaryDataPoJo> guguaranteeObj = new ArrayList<>();
                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lableList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);

                    others.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, ProductEnum.PRODUCT_IMGS.getAttr(), new JSONArray()));
                    others.put(ProductConstant.TRANSFORM_UNIT_RATE, formData.getJSONArray(ProductConstant.TRANSFORM_UNIT_RATE));
                    formData.remove(ProductConstant.TRANSFORM_UNIT_RATE);

                    if (Objects.equals(groupId, Long.valueOf(ListGroupEnum.WARNING_SEARCH.getCode()))) {
                        ProductWarehouseEntity productWarehouseEntity = formDataItem.getProductWarehouseEntity();
                        others.put("warehouseName", productWarehouseEntity.getWarehouseName());
                        if (productWarehouseEntity.getNum() > productWarehouseEntity.getStockUpperLimit()) {
                            // 超上限
                            others.put("overLimitType", 1);
                            others.put("overNum", productWarehouseEntity.getNum() - productWarehouseEntity.getStockUpperLimit());
                        } else {
                            // 超下限
                            others.put("overLimitType", 2);
                            others.put("overNum", productWarehouseEntity.getStockLowerLimit() - productWarehouseEntity.getNum());
                        }
                        // 预警查询
                        JSONArray warningInfoList;
                        try {
                            JSONObject warningObj = FastJsonHelper.getJsonObjectFromFormData(formData, ListOptionEnum.MULTI_SPEC.getAttr());
                            warningInfoList = warningObj.getJSONArray("value");
                        } catch (Exception e) {
                            warningInfoList = new JSONArray();
                        }
                        others.put("warning", warningInfoList);
                    } else if (Objects.equals(ListGroupEnum.getByCode(groupId.intValue()).getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                        // 保质期查询
//                        summaryList.add(commonHelp.setSummary(I18nMessageUtil.getMessage(ProductEnum.SERIALNO.getAttrName()), formData.getString(ProductEnum.SERIALNO.getAttr())));
//                        summaryList.add(commonHelp.setSummary(I18nMessageUtil.getMessage(ProductEnum.SPECIFICATION.getAttrName()), formData.getString(ProductEnum.SPECIFICATION.getAttr())));
                        JSONArray guaranteeInfoList;
                        try {
                            JSONObject warningObj = new JSONObject();
                            warningObj.put(SelectProductEnum.WAREHOUSE.getSaasAttr(), formData.getString(SelectProductEnum.WAREHOUSE.getSaasAttr()));
                            warningObj.put(SelectProductEnum.STOCK.getSaasAttr(), formData.getString(SelectProductEnum.STOCK.getSaasAttr()));
                            warningObj.put(SelectProductEnum.COST.getSaasAttr(), formData.getString(SelectProductEnum.COST.getSaasAttr()));
                            warningObj.put("costTotal", formData.getString(SelectProductEnum.TOTAL_COST.getSaasAttr()));
                            guaranteeInfoList = new JSONArray();
                            guaranteeInfoList.add(warningObj);
                        } catch (Exception e) {
                            guaranteeInfoList = new JSONArray();
                        }
                        // 剩余天数以及批次
                        List<SummaryDataPoJo> guaranteeAndBatchPoJoList = new ArrayList<>();
                        SummaryDataPoJo batchDataPoJo = new SummaryDataPoJo(batchFieldAttr.getAttr(), batchFieldAttr.getAttrName(), batchFieldAttr.getFieldType(), Collections.singletonList(formData.getString(batchFieldAttr.getAttr())));
                        SummaryDataPoJo guaranteeSearchDataPoJo = new SummaryDataPoJo(guaranteeSearchFieldAttr.getAttr(), guaranteeSearchFieldAttr.getAttrName(), guaranteeSearchFieldAttr.getFieldType(), Collections.singletonList(formData.getString(guaranteeSearchFieldAttr.getAttr())));
                        if (formData.getString(guaranteeSearchDataPoJo.getAttr()).startsWith("-")) {
                            guaranteeSearchDataPoJo.setColor("#FF0000");
                        }
                        guaranteeAndBatchPoJoList.add(batchDataPoJo);
                        guaranteeAndBatchPoJoList.add(guaranteeSearchDataPoJo);
                        batctList.add(guaranteeAndBatchPoJoList);
                        // 仓库以及库存
                        List<SummaryDataPoJo> warehouseAndStockPoJoList = new ArrayList<>();
                        SummaryDataPoJo warehouseDataPoJo = new SummaryDataPoJo(warehouseField.getAttr(), warehouseField.getAttrName(), warehouseField.getFieldType(), Collections.singletonList(formData.getString(warehouseField.getAttr())));
                        SummaryDataPoJo stockDataPoJo = new SummaryDataPoJo(stockFieldAttr.getAttr(), stockFieldAttr.getAttrName(), stockFieldAttr.getFieldType(), Collections.singletonList(formData.getString(stockFieldAttr.getAttr())));
                        stockDataPoJo.setColor("#ff8e3d");
                        warehouseAndStockPoJoList.add(warehouseDataPoJo);
                        warehouseAndStockPoJoList.add(stockDataPoJo);
                        batctList.add(warehouseAndStockPoJoList);
                        others.put("warning", guaranteeInfoList);
//                        if (!Objects.equals(formData.getLongValue(SelectProductEnum.PRODUCE_DATE.getSaasAttr()), 0L)) {
                            SummaryDataPoJo expireDate = new SummaryDataPoJo(SelectProductEnum.EXPIRE_DATE.getSaasAttr(), SelectProductEnum.EXPIRE_DATE.getAttrName(), SelectProductEnum.EXPIRE_DATE.getFieldType(), formData.getLongValue(SelectProductEnum.EXPIRE_DATE.getSaasAttr()) == 0L ? Collections.singletonList("--") : Collections.singletonList(DateTimeUtil.getStringEpochSecond(formData.getLongValue(SelectProductEnum.EXPIRE_DATE.getSaasAttr()), DateTypeEnum.YMD.getAlias())));
                            SummaryDataPoJo produceDate = new SummaryDataPoJo(SelectProductEnum.PRODUCE_DATE.getSaasAttr(), SelectProductEnum.PRODUCE_DATE.getAttrName(), SelectProductEnum.PRODUCE_DATE.getFieldType(), formData.getLongValue(SelectProductEnum.PRODUCE_DATE.getSaasAttr()) == 0L ? Collections.singletonList("--") : Collections.singletonList(DateTimeUtil.getStringEpochSecond(formData.getLongValue(SelectProductEnum.PRODUCE_DATE.getSaasAttr()), DateTypeEnum.YMD.getAlias())));
                            SummaryDataPoJo guaranteePeriod = new SummaryDataPoJo(SelectProductEnum.GUARANTEE_PERIOD.getSaasAttr(), SelectProductEnum.GUARANTEE_PERIOD.getAttrName(), SelectProductEnum.GUARANTEE_PERIOD.getFieldType(), formData.getString(SelectProductEnum.GUARANTEE_PERIOD.getSaasAttr())== null ? Collections.singletonList("--") : Collections.singletonList(formData.getString(SelectProductEnum.GUARANTEE_PERIOD.getSaasAttr())));
                            guguaranteeObj.add(expireDate);
                            guguaranteeObj.add(produceDate);
                            guguaranteeObj.add(guaranteePeriod);
//                        }
                    } else {
                        // 库存查询
                        JSONArray stockInfoList = getProductWarehouseInfo(formDataItem);
                        summaryList.removeIf(summaryDataPoJo -> Objects.equals(summaryDataPoJo.getAttr(), ProductEnum.STOCK.getAttr()));
                        SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                        summaryDataPoJo.setAttr(ProductEnum.STOCK.getAttr());
                        summaryDataPoJo.setAttrName(ProductEnum.STOCK.getAttrName());
                        summaryDataPoJo.setFieldType(ProductEnum.STOCK.getFieldType());
                        summaryDataPoJo.setColor("orange");
                        summaryDataPoJo.setValue(Collections.singletonList(((JSONObject) stockInfoList.get(0)).get("stock")));
                        SummaryDataPoJo availableStockPoJo = new SummaryDataPoJo();
                        availableStockPoJo.setAttr("availableStock");
                        availableStockPoJo.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.AVAILABLE_STOCK));
                        availableStockPoJo.setFieldType(ProductEnum.STOCK.getFieldType());
                        availableStockPoJo.setColor("orange");
                        //设置可用库存量值
                        if (!contractProductEntityMap.isEmpty() && Objects.nonNull(contractProductEntityMap.get(formDataItem.getDataId()))){
                            if (Objects.nonNull(formData.get(ProductEnum.STOCK.getAttr()))) {
                                Double availableStock = Arith.sub(formData.getDouble(ProductEnum.STOCK.getAttr()), contractProductEntityMap.get(formDataItem.getDataId()).getSumNum());
                                availableStockPoJo.setValue(Collections.singletonList(availableStock));
                            } else {
                                availableStockPoJo.setValue(new ArrayList<>());
                            }
                        }else {
                            //如果没有待出库数量，可用库存量=库存
                            availableStockPoJo.setValue(Collections.singletonList(((JSONObject) stockInfoList.get(0)).get("stock")));
                        }
                        summaryList.add(summaryDataPoJo);
                        summaryList.add(availableStockPoJo);
                        others.put("warning", stockInfoList);
                    }
                    formData = formDataItem.getData();
                    Double stock = getDoubleOrDefaultFromFormData(formData, ProductEnum.STOCK.getAttr(), 0D);
                    String unit = FastJsonHelper.getStringOrDefaultFromFormData(formData, ProductEnum.UNIT.getAttr(), "");
                    stock = attrDecimalPrecisionHelper.setPrecision(stock,formDataListVO.getExplainMap().get(ProductEnum.STOCK.getAttr()).getAccuracy());
                    others.put(ProductEnum.STOCK.getSaasAttr(), stock + unit);
                    appItemList.add(new AppListPojo(dataId, titleList, summaryList, null, lableList, others, batctList, guguaranteeObj));
                }
                break;
            case REIMBURSEMENT_FORM:
//                Long reimbursementFormGroupId = formDataListDTO.getListGroupId();
//                if (!Objects.equals(reimbursementFormGroupId, Long.valueOf(ListGroupEnum.REIMBURSEMENT_FORM_ALl.getCode()))) {
//                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
//                }
                setSpecialSearchAttr(formDataListDTO);
                formDataListVO = reimbursementFormList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lableList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);

                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lableList, new JSONObject()));
                }
                break;
            case EXPENSE:
//                Long reimbursementFormGroupId = formDataListDTO.getListGroupId();
////                if (!Objects.equals(reimbursementFormGroupId, Long.valueOf(ListGroupEnum.REIMBURSEMENT_FORM_ALl.getCode()))) {
////                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
////                }
                setSpecialSearchAttr(formDataListDTO);
                formDataListVO = expenseList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lableList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);

                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lableList, new JSONObject()));
                }
                break;
            case STOCK_FLOW_BILL:
                formDataListVO = stockFlowBillList(formDataListDTO);
                headList = formDataListVO.getHeadList();
                FieldAttrEntity outInFieldAttr = new FieldAttrEntity();
                FieldAttrEntity remainFieldAttr = new FieldAttrEntity();
                for (FieldAttrEntity fieldAttrEntity : headList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), StockFlowBillEnum.OUT_IN_RECORD.getAttr())) {
                        outInFieldAttr = fieldAttrEntity;
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), StockFlowBillEnum.REMAINING_STOCK.getAttr())) {
                        remainFieldAttr = fieldAttrEntity;
                    }
                }
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    List<SummaryDataPoJo> summaryList = new ArrayList<>();
                    List<List<SummaryDataPoJo>> stockFlowBillList = new ArrayList<>();
                    List<FormTitlePoJo> titleList = new ArrayList<>();
                    JSONObject others = new JSONObject();
                    formData.remove(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr());
                    summaryList.add(new SummaryDataPoJo(StockFlowBillEnum.SERIALNO.getAttr(),StockFlowBillEnum.SERIALNO.getAttrName(),StockFlowBillEnum.SERIALNO.getFieldType(), Collections.singletonList(formData.getString(StockFlowBillEnum.SERIALNO.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(StockFlowBillEnum.SPECIFICATION.getAttr(),StockFlowBillEnum.SPECIFICATION.getAttrName(),StockFlowBillEnum.SPECIFICATION.getFieldType(), Collections.singletonList(formData.getString(StockFlowBillEnum.SPECIFICATION.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(StockFlowBillEnum.TIME.getAttr(),StockFlowBillEnum.TIME.getAttrName(),StockFlowBillEnum.TIME.getFieldType(), Collections.singletonList(formData.getString(StockFlowBillEnum.TIME.getAttr()))));
                    titleList.add(new FormTitlePoJo(StockFlowBillEnum.NAME.getAttr(), null, StockFlowBillEnum.NAME.getAttrName(), Collections.singletonList(formData.getString(StockFlowBillEnum.NAME.getAttr())), null));
                    others.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), formData.getJSONArray(ProductEnum.PRODUCT_IMGS.getSaasAttr()));

                    handleItemPojo(formData,StockFlowBillEnum.TYPE.getAttr());
                    JSONObject baseInfo = new JSONObject();
                    baseInfo.putAll(formData);
                    JSONObject outInStock = new JSONObject();
                    outInStock.putAll(formData.getJSONArray(StockFlowBillEnum.OUT_IN_RECORD.getAttr()).getJSONObject(0));
                    JSONObject remainStock = new JSONObject();
                    remainStock.putAll(formData.getJSONArray(StockFlowBillEnum.REMAINING_STOCK.getAttr()).getJSONObject(0));
                    baseInfo.remove(StockFlowBillEnum.NAME.getAttr());
                    baseInfo.remove(StockFlowBillEnum.SERIALNO.getAttr());
                    baseInfo.remove(StockFlowBillEnum.SPECIFICATION.getAttr());
                    baseInfo.remove(StockFlowBillEnum.OUT_IN_RECORD.getAttr());
                    baseInfo.remove(StockFlowBillEnum.REMAINING_STOCK.getAttr());
                    baseInfo.remove(ProductEnum.PRODUCT_IMGS.getSaasAttr());
                    setStockFlowBillList(outInFieldAttr, formData.getJSONArray(StockFlowBillEnum.OUT_IN_RECORD.getAttr()).getJSONObject(0), stockFlowBillList);
                    setStockFlowBillList(remainFieldAttr, formData.getJSONArray(StockFlowBillEnum.REMAINING_STOCK.getAttr()).getJSONObject(0), stockFlowBillList);
                    others.put("baseInfo", baseInfo);
                    others.put(StockFlowBillEnum.OUT_IN_RECORD.getAttr(), outInStock);
                    others.put(StockFlowBillEnum.REMAINING_STOCK.getAttr(), remainStock);
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, null, others, stockFlowBillList));
                }
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                return new ListAppVO(appItemList, totalCount, getAppListAddPermission(formDataListVO), formDataListVO.getHeadList());
            case STOCK_STANDING_BOOK:
                formDataListVO = stockStandingBookList(formDataListDTO);
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                remainFieldAttr = new FieldAttrEntity();
                for (FieldAttrEntity fieldAttrEntity : formDataListVO.getHeadList()) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), StockStandingBookEnum.REMAINING_STOCK.getAttr())) {
                        remainFieldAttr = fieldAttrEntity;
                    }
                }
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    List<SummaryDataPoJo> summaryList = new ArrayList<>();
                    List<List<SummaryDataPoJo>> stockFlowBillList = new ArrayList<>();
                    List<FormTitlePoJo> titleList = new ArrayList<>();
                    // 保证JSON的顺序 前端需要用
                    formData.remove(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr());
                    JSONObject others = new JSONObject(true);
                    summaryList.add(new SummaryDataPoJo(StockStandingBookEnum.SERIALNO.getAttr(),StockStandingBookEnum.SERIALNO.getAttrName(),StockStandingBookEnum.SERIALNO.getFieldType(), Collections.singletonList(formData.getString(StockStandingBookEnum.SERIALNO.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(StockStandingBookEnum.SPECIFICATION.getAttr(),StockStandingBookEnum.SPECIFICATION.getAttrName(),StockStandingBookEnum.SPECIFICATION.getFieldType(), Collections.singletonList(formData.getString(StockStandingBookEnum.SPECIFICATION.getAttr()))));
                    titleList.add(new FormTitlePoJo(StockStandingBookEnum.NAME.getAttr(), null, StockStandingBookEnum.NAME.getAttrName(), Collections.singletonList(formData.getString(StockStandingBookEnum.NAME.getAttr())), null));
                    others.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), formData.getJSONArray(ProductEnum.PRODUCT_IMGS.getSaasAttr()));
                    JSONObject baseInfo = new JSONObject();
                    baseInfo.putAll(formData);
                    JSONObject outStock = new JSONObject();
                    if (formData.getJSONArray(StockStandingBookEnum.PERIOD_OUTSTOCK.getAttr()) != null && !formData.getJSONArray(StockStandingBookEnum.PERIOD_OUTSTOCK.getAttr()).isEmpty()) {
                        outStock.putAll(formData.getJSONArray(StockStandingBookEnum.PERIOD_OUTSTOCK.getAttr()).getJSONObject(0));
                    }
                    JSONObject remainStock = new JSONObject();
                    if (formData.getJSONArray(StockStandingBookEnum.REMAINING_STOCK.getAttr()) != null && !formData.getJSONArray(StockStandingBookEnum.REMAINING_STOCK.getAttr()).isEmpty()) {
                        remainStock.putAll(formData.getJSONArray(StockStandingBookEnum.REMAINING_STOCK.getAttr()).getJSONObject(0));
                    }
                    JSONObject inStock = new JSONObject();
                    if (formData.getJSONArray(StockStandingBookEnum.PERIOD_INSTOCK.getAttr()) != null && !formData.getJSONArray(StockStandingBookEnum.PERIOD_INSTOCK.getAttr()).isEmpty()) {
                        inStock.putAll(formData.getJSONArray(StockStandingBookEnum.PERIOD_INSTOCK.getAttr()).getJSONObject(0));
                    }
                    JSONObject oriStock = new JSONObject();
                    if (formData.getJSONArray(StockStandingBookEnum.ORI_STOCK.getAttr()) != null && !formData.getJSONArray(StockStandingBookEnum.ORI_STOCK.getAttr()).isEmpty()) {
                        oriStock.putAll(formData.getJSONArray(StockStandingBookEnum.ORI_STOCK.getAttr()).getJSONObject(0));
                    }
                    baseInfo.remove(StockStandingBookEnum.NAME.getAttr());
                    baseInfo.remove(StockStandingBookEnum.SERIALNO.getAttr());
                    baseInfo.remove(StockStandingBookEnum.SPECIFICATION.getAttr());
                    baseInfo.remove(StockStandingBookEnum.PERIOD_INSTOCK.getAttr());
                    baseInfo.remove(StockStandingBookEnum.REMAINING_STOCK.getAttr());
                    baseInfo.remove(StockStandingBookEnum.ORI_STOCK.getAttr());
                    baseInfo.remove(StockStandingBookEnum.PERIOD_OUTSTOCK.getAttr());
                    baseInfo.remove(ProductEnum.PRODUCT_IMGS.getSaasAttr());
                    setStockStandingBookList(remainFieldAttr, formData.getJSONArray(StockStandingBookEnum.REMAINING_STOCK.getAttr()).getJSONObject(0), stockFlowBillList);
                    others.put("baseInfo", baseInfo);
                    others.put(StockStandingBookEnum.ORI_STOCK.getAttr(), oriStock);
                    others.put(StockStandingBookEnum.PERIOD_INSTOCK.getAttr(), inStock);
                    others.put(StockStandingBookEnum.PERIOD_OUTSTOCK.getAttr(), outStock);
                    others.put(StockStandingBookEnum.REMAINING_STOCK.getAttr(), remainStock);
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, null, others, stockFlowBillList));
                }
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                return new ListAppVO(appItemList, totalCount, getAppListAddPermission(formDataListVO), formDataListVO.getHeadList());
            case BATCH_FLOW_BILL:
                formDataListVO = batchFlowBillList(formDataListDTO);
                headList = formDataListVO.getHeadList();
                outInFieldAttr = null;
                remainFieldAttr = null;
                for (FieldAttrEntity fieldAttrEntity : headList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), BatchFlowBillEnum.OUT_IN_RECORD.getAttr())) {
                        outInFieldAttr = fieldAttrEntity;
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), BatchFlowBillEnum.REMAINING_STOCK.getAttr())) {
                        remainFieldAttr = fieldAttrEntity;
                    }
                }
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    List<SummaryDataPoJo> summaryList = new ArrayList<>();
                    List<List<SummaryDataPoJo>> batchFlowBillList = new ArrayList<>();
                    List<FormTitlePoJo> titleList = new ArrayList<>();
                    JSONObject others = new JSONObject();
                    formData.remove(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr());
                    summaryList.add(new SummaryDataPoJo(StockFlowBillEnum.SERIALNO.getAttr(),BatchFlowBillEnum.SERIAL_NO.getAttrName(),BatchFlowBillEnum.SERIAL_NO.getFieldType(), Collections.singletonList(formData.getString(BatchFlowBillEnum.SERIAL_NO.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(BatchFlowBillEnum.SPECIFICATION.getAttr(),BatchFlowBillEnum.SPECIFICATION.getAttrName(),BatchFlowBillEnum.SPECIFICATION.getFieldType(), Collections.singletonList(formData.getString(BatchFlowBillEnum.SPECIFICATION.getAttr()))));
                    titleList.add(new FormTitlePoJo(BatchFlowBillEnum.NAME.getAttr(), null, BatchFlowBillEnum.NAME.getAttrName(), Collections.singletonList(formData.getString(BatchFlowBillEnum.NAME.getAttr())), null));
                    others.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), formData.getJSONArray(ProductEnum.PRODUCT_IMGS.getSaasAttr()));
                    JSONObject baseInfo = new JSONObject(true);
                    baseInfo.put(BatchFlowBillEnum.BATCH.getAttr(), formData.get(BatchFlowBillEnum.BATCH.getAttr()));
                    if (Objects.nonNull(formData.get(BatchFlowBillEnum.PRODUCE_DATE.getAttr())) && !Objects.equals(formData.getLong(BatchFlowBillEnum.PRODUCE_DATE.getAttr()), 0L)) {
                        baseInfo.put(BatchFlowBillEnum.PRODUCE_DATE.getAttr(), formData.get(BatchFlowBillEnum.PRODUCE_DATE.getAttr()));
                        baseInfo.put(BatchFlowBillEnum.GUARANTEE_PERIOD.getAttr(), formData.get(BatchFlowBillEnum.GUARANTEE_PERIOD.getAttr()));
                        baseInfo.put(BatchFlowBillEnum.EXPIRE_DATE.getAttr(), formData.get(BatchFlowBillEnum.EXPIRE_DATE.getAttr()));
                    }
                    baseInfo.put(BatchFlowBillEnum.TIME.getAttr(), formData.get(BatchFlowBillEnum.TIME.getAttr()));
                    baseInfo.put(BatchFlowBillEnum.SHEET_NO.getAttr(), formData.get(BatchFlowBillEnum.SHEET_NO.getAttr()));
                    baseInfo.put(BatchFlowBillEnum.TYPE.getAttr(), ItemUtil.parseItemPoJoFromFormData2String(formData, BatchFlowBillEnum.TYPE.getAttr(), ""));
                    baseInfo.put(BatchFlowBillEnum.BUSINESS_ID.getAttr(), formData.get(BatchFlowBillEnum.BUSINESS_ID.getAttr()));
                    baseInfo.put(BatchFlowBillEnum.WAREHOUSE_ID.getAttr(), formData.get(BatchFlowBillEnum.WAREHOUSE_ID.getAttr()));
                    baseInfo.put(BatchFlowBillEnum.UNIT.getAttr(), formData.get(BatchFlowBillEnum.UNIT.getAttr()));
                    JSONObject outInStock = new JSONObject();
                    outInStock.putAll(formData.getJSONArray(BatchFlowBillEnum.OUT_IN_RECORD.getAttr()).getJSONObject(0));
                    JSONObject remainStock = new JSONObject();
                    remainStock.putAll(formData.getJSONArray(BatchFlowBillEnum.REMAINING_STOCK.getAttr()).getJSONObject(0));
                    setStockFlowBillList(outInFieldAttr, formData.getJSONArray(BatchFlowBillEnum.OUT_IN_RECORD.getAttr()).getJSONObject(0), batchFlowBillList);
                    setStockFlowBillList(remainFieldAttr, formData.getJSONArray(BatchFlowBillEnum.REMAINING_STOCK.getAttr()).getJSONObject(0), batchFlowBillList);
                    others.put("baseInfo", baseInfo);
                    others.put(BatchFlowBillEnum.OUT_IN_RECORD.getAttr(), outInStock);
                    others.put(BatchFlowBillEnum.REMAINING_STOCK.getAttr(), remainStock);
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, null, others, batchFlowBillList, formData.getString(BatchFlowBillEnum.BATCH.getAttr())));
                }
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                return new ListAppVO(appItemList, totalCount, getAppListAddPermission(formDataListVO), formDataListVO.getHeadList());
            case SEQ_SEARCH:
                formDataListVO = productSerialList(formDataListDTO);
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                headList = formDataListVO.getHeadList();
                FieldAttrEntity statusFieldAttr = null;
                FieldAttrEntity warehouseFieldAttr = null;
                for (FieldAttrEntity fieldAttrEntity : headList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ProductSerialBalanceEnum.STATUS.getAttr())) {
                        statusFieldAttr = fieldAttrEntity;
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), ProductSerialBalanceEnum.WAREHOUSE_ID.getAttr())) {
                        warehouseFieldAttr = fieldAttrEntity;
                    }
                }
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    List<SummaryDataPoJo> summaryList = new ArrayList<>();
                    List<List<SummaryDataPoJo>> productSerialList = new ArrayList<>();
                    List<FormTitlePoJo> titleList = new ArrayList<>();
                    JSONObject others = new JSONObject();
                    summaryList.add(new SummaryDataPoJo(ProductSerialBalanceEnum.SERIALNO.getAttr(),ProductSerialBalanceEnum.SERIALNO.getAttrName(),ProductSerialBalanceEnum.SERIALNO.getFieldType(), Collections.singletonList(formData.getString(BatchFlowBillEnum.SERIAL_NO.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(ProductSerialBalanceEnum.SPECIFICATION.getAttr(),ProductSerialBalanceEnum.SPECIFICATION.getAttrName(),ProductSerialBalanceEnum.SPECIFICATION.getFieldType(), Collections.singletonList(formData.getString(ProductSerialBalanceEnum.SPECIFICATION.getAttr()))));
                    titleList.add(new FormTitlePoJo(ProductSerialBalanceEnum.SEQ.getAttr(), null, ProductSerialBalanceEnum.SEQ.getAttrName(), Collections.singletonList(formData.getString(ProductSerialBalanceEnum.SEQ.getAttr())), null));
                    others.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), formData.getJSONArray(ProductEnum.PRODUCT_IMGS.getSaasAttr()));
                    JSONObject baseInfo = new JSONObject();
                    baseInfo.putAll(formData);
                    setProductSerialFlowList(warehouseFieldAttr, formData.getString(ProductSerialBalanceEnum.WAREHOUSE_ID.getAttr()), productSerialList);
                    setProductSerialFlowList(statusFieldAttr, formData.getString(ProductSerialBalanceEnum.STATUS.getAttr()), productSerialList);
                    others.put("baseInfo", baseInfo);
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, null, others, productSerialList));
                }
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                return new ListAppVO(appItemList, totalCount, getAppListAddPermission(formDataListVO), formDataListVO.getHeadList());
            case MARKETING_ACTIVITY_MANAGEMENT:
                formDataListVO = marketingActivity(formDataListDTO);
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    Integer activityStatus = formDataItem.getActivityStatus();
                    Long addTimeObject = formData.getLong(MarketingActivityManagementEnum.ADD_TIME.getAttr());
                    String addTime = DateTimeUtil.getDateStringEpochSecond(addTimeObject);
                    List<SummaryDataPoJo> summaryList = new ArrayList<>();
                    List<List<SummaryDataPoJo>> marketingActivityList = new ArrayList<>();
                    List<FormTitlePoJo> titleList = new ArrayList<>();
                    JSONObject others = new JSONObject();
                    summaryList.add(new SummaryDataPoJo(MarketingActivityManagementEnum.TYPE.getAttr(),MarketingActivityManagementEnum.TYPE.getAttrName(),MarketingActivityManagementEnum.TYPE.getFieldType(), Collections.singletonList(formData.getString(MarketingActivityManagementEnum.TYPE.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(MarketingActivityManagementEnum.ACTIVITY_TIME.getAttr(),MarketingActivityManagementEnum.ACTIVITY_TIME.getAttrName(),MarketingActivityManagementEnum.ACTIVITY_TIME.getFieldType(), Collections.singletonList(formData.getString(MarketingActivityManagementEnum.ACTIVITY_TIME.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(MarketingActivityManagementEnum.CREATOR_ID.getAttr(),MarketingActivityManagementEnum.CREATOR_ID.getAttrName(),MarketingActivityManagementEnum.CREATOR_ID.getFieldType(), Collections.singletonList(formData.getString(MarketingActivityManagementEnum.CREATOR_ID.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(MarketingActivityManagementEnum.ADD_TIME.getAttr(),MarketingActivityManagementEnum.ADD_TIME.getAttrName(),MarketingActivityManagementEnum.ADD_TIME.getFieldType(), Collections.singletonList(addTime)));
                    titleList.add(new FormTitlePoJo(MarketingActivityManagementEnum.NAME.getAttr(), null, MarketingActivityManagementEnum.NAME.getAttrName(), Collections.singletonList(formData.getString(MarketingActivityManagementEnum.NAME.getAttr())), null));
                    others.put(StringConstant.STATUS, MarketingStatusEnum.getByCode(activityStatus));
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, null, others, marketingActivityList));
                }
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                return new ListAppVO(appItemList, totalCount, getAppListAddPermission(formDataListVO), formDataListVO.getHeadList());
            case PROMOTION_ACTIVITY_MANAGEMENT:
                formDataListVO = promotionActivity(formDataListDTO);
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    Integer activityStatus = formDataItem.getActivityStatus();
                    Long addTimeObject = formData.getLong(PromotionActivityManagementEnum.ADD_TIME.getAttr());
                    String addTime = DateTimeUtil.getDateStringEpochSecond(addTimeObject);
                    List<SummaryDataPoJo> summaryList = new ArrayList<>();
                    List<List<SummaryDataPoJo>> marketingActivityList = new ArrayList<>();
                    List<FormTitlePoJo> titleList = new ArrayList<>();
                    JSONObject others = new JSONObject();
                    summaryList.add(new SummaryDataPoJo(PromotionActivityManagementEnum.TYPE.getAttr(),PromotionActivityManagementEnum.TYPE.getAttrName(),PromotionActivityManagementEnum.TYPE.getFieldType(), Collections.singletonList(formData.getString(PromotionActivityManagementEnum.TYPE.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(PromotionActivityManagementEnum.ACTIVITY_TIME.getAttr(),PromotionActivityManagementEnum.ACTIVITY_TIME.getAttrName(),PromotionActivityManagementEnum.ACTIVITY_TIME.getFieldType(), Collections.singletonList(formData.getString(PromotionActivityManagementEnum.ACTIVITY_TIME.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(PromotionActivityManagementEnum.CREATOR_ID.getAttr(),PromotionActivityManagementEnum.CREATOR_ID.getAttrName(),PromotionActivityManagementEnum.CREATOR_ID.getFieldType(), Collections.singletonList(formData.getString(PromotionActivityManagementEnum.CREATOR_ID.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(PromotionActivityManagementEnum.ADD_TIME.getAttr(),PromotionActivityManagementEnum.ADD_TIME.getAttrName(),PromotionActivityManagementEnum.ADD_TIME.getFieldType(), Collections.singletonList(addTime)));
                    titleList.add(new FormTitlePoJo(PromotionActivityManagementEnum.NAME.getAttr(), null, PromotionActivityManagementEnum.NAME.getAttrName(), Collections.singletonList(formData.getString(PromotionActivityManagementEnum.NAME.getAttr())), null));
                    others.put(StringConstant.STATUS, MarketingStatusEnum.getByCode(activityStatus));
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, null, others, marketingActivityList));
                }
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                return new ListAppVO(appItemList, totalCount, getAppListAddPermission(formDataListVO), formDataListVO.getHeadList());
            case PRICE_SET:
                formDataListVO = productPriceList(formDataListDTO);
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    JSONObject productPriceData = paasFormDataEntityExt.getData();
                    List<FormTitlePoJo> titleList = new ArrayList<>();
                    List<SummaryDataPoJo> summaryList = new ArrayList<>();
                    JSONObject others = new JSONObject();
                    List<SummaryDataPoJo> productPriceList = new ArrayList<>();
                    summaryList.add(new SummaryDataPoJo(PriceProductEnum.SPECIFICATION.getAttr(),PriceProductEnum.SPECIFICATION.getAttrName(),PriceProductEnum.SPECIFICATION.getFieldType(), Collections.singletonList(productPriceData.getString(PriceProductEnum.SPECIFICATION.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(PriceProductEnum.UNIT.getAttr(),PriceProductEnum.UNIT.getAttrName(),PriceProductEnum.UNIT.getFieldType(), Collections.singletonList(productPriceData.getString(PriceProductEnum.UNIT.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(PriceSetEnum.NAME.getAttr(),PriceSetEnum.NAME.getAttrName(),PriceSetEnum.NAME.getFieldType(), Collections.singletonList(productPriceData.getString(PriceSetEnum.NAME.getAttr()))));
                    SummaryDataPoJo sellingPrice = new SummaryDataPoJo(PriceProductEnum.SELLING_PRICE.getAttr(), PriceProductEnum.SELLING_PRICE.getAttrName(), PriceProductEnum.SELLING_PRICE.getFieldType(), Collections.singletonList(productPriceData.getString(PriceProductEnum.SELLING_PRICE.getAttr())));
                    sellingPrice.setColor("orange");
                    summaryList.add(sellingPrice);
                    titleList.add(new FormTitlePoJo(PriceProductEnum.NAME.getAttr(), null, PriceProductEnum.NAME.getAttrName(), Collections.singletonList(productPriceData.getString(PriceProductEnum.NAME.getAttr())), null));
                    others.put(PriceProductEnum.PRODUCT_IMGS.getSaasAttr(), FastJsonHelper.getJsonArrOrDefaultFromFormData(productPriceData, PriceProductEnum.PRODUCT_IMGS.getAttr(), new JSONArray()));
                    setProductPriceList(productPriceData, productPriceList);
                    appItemList.add(new AppListPojo(paasFormDataEntityExt.getDataId(), titleList, summaryList, others, productPriceList));
                }
                return new ListAppVO(appItemList, totalCount, getAppListAddPermission(formDataListVO), formDataListVO.getHeadList(), true);
            case FUND_TRANSFER:
                formDataListVO = fundTransferList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();
                    String amount = formData.getDoubleValue(FundTransferEnum.AMOUNT.getAttr()) + UnitEnum.MONEY.getName();
                    others.put("amount", amount);
                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            case COST_ADJUST:
                formDataListVO = costAdjustList(formDataListDTO);
                totalCount = formDataListVO.getPageHelper().getRowsCount();
                paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt formDataItem : paasFormDataESList) {
                    JSONObject formData = formDataItem.getData();
                    JSONObject others = new JSONObject();
                    List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
                    List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
                    summaryList.add(new SummaryDataPoJo(CostAdjustEnum.CREATOR_ID.getAttr(),CostAdjustEnum.CREATOR_ID.getAttrName(),CostAdjustEnum.CREATOR_ID.getFieldType(), Collections.singletonList(formData.getString(CostAdjustEnum.CREATOR_ID.getAttr()))));
                    summaryList.add(new SummaryDataPoJo(CostAdjustEnum.ADD_TIME.getAttr(),CostAdjustEnum.ADD_TIME.getAttrName(),CostAdjustEnum.ADD_TIME.getFieldType(), Collections.singletonList(DateUtil.getString(formData.getInteger(CostAdjustEnum.ADD_TIME.getAttr())))));
                    if (titleList.isEmpty()) {
                        FormTitlePoJo titlePoJo = new FormTitlePoJo();
                        titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                        titleList.add(titlePoJo);
                    }
                    appItemList.add(new AppListPojo(formDataItem.getDataId(), titleList, summaryList, null, lablesList, others));
                }
                break;
            default:
                break;
        }

        return new ListAppVO(appItemList, totalCount, getAppListAddPermission(formDataListVO));
    }

    private void handleItemPojo(JSONObject formData, String attr) {
        Object o = formData.get(attr);
        if (Objects.nonNull(o) && o instanceof ItemPoJo) {
            formData.put(attr, ((ItemPoJo) o).getText());
        }
    }


    private void setProductPriceList(JSONObject productPriceData, List<SummaryDataPoJo> productPriceList) {
        productPriceList.add(new SummaryDataPoJo(PriceSetEnum.NAME.getAttr(),PriceSetEnum.NAME.getAttrName(),PriceSetEnum.NAME.getFieldType(), Collections.singletonList(productPriceData.getString(PriceSetEnum.NAME.getAttr()))));
        productPriceList.add(new SummaryDataPoJo(PriceProductEnum.PRICE.getAttr(),PriceProductEnum.PRICE.getAttrName(),PriceProductEnum.PRICE.getFieldType(), Collections.singletonList(productPriceData.getString(PriceProductEnum.PRICE.getAttr()))));
        productPriceList.add(new SummaryDataPoJo(PriceProductEnum.DISCOUNT.getAttr(),PriceProductEnum.DISCOUNT.getAttrName(),PriceProductEnum.DISCOUNT.getFieldType(), Collections.singletonList(productPriceData.getString(PriceProductEnum.DISCOUNT.getAttr()))));
        productPriceList.add(new SummaryDataPoJo(PriceProductEnum.SELLING_PRICE.getAttr(),PriceProductEnum.SELLING_PRICE.getAttrName(),PriceProductEnum.SELLING_PRICE.getFieldType(), Collections.singletonList(productPriceData.getString(PriceProductEnum.SELLING_PRICE.getAttr()))));
        productPriceList.add(new SummaryDataPoJo(PriceProductEnum.SELLING_PRICE_UP.getAttr(),PriceProductEnum.SELLING_PRICE_UP.getAttrName(),PriceProductEnum.SELLING_PRICE_UP.getFieldType(), Collections.singletonList(productPriceData.getString(PriceProductEnum.SELLING_PRICE_UP.getAttr()))));
        productPriceList.add(new SummaryDataPoJo(PriceProductEnum.SELLING_PRICE_DOWN.getAttr(),PriceProductEnum.SELLING_PRICE_DOWN.getAttrName(),PriceProductEnum.SELLING_PRICE_DOWN.getFieldType(), Collections.singletonList(productPriceData.getString(PriceProductEnum.SELLING_PRICE_DOWN.getAttr()))));

    }

    private void setStockFlowBillList(FieldAttrEntity fieldAttrEntity, JSONObject jsonObject, List<List<SummaryDataPoJo>> stockFlowBillList) {
        List<SummaryDataPoJo> summaryDataPoJoList = new ArrayList<>();
        stockFlowBillList.add(summaryDataPoJoList);
        List<FieldAttrEntity> subExplainList = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), FieldAttrEntity.class);
        String parentName = fieldAttrEntity.getAttrName();
        subExplainList.forEach(item -> {
            if (!Objects.equals(item.getAttr(), FlowSubFormEnum.COST_TOTAL.getAttr())) {
                SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo(item.getAttr(),parentName + item.getAttrName(),item.getFieldType(), Collections.singletonList(jsonObject.get(item.getAttr())));
                summaryDataPoJoList.add(summaryDataPoJo);
            }
        });
    }

    private void setStockStandingBookList(FieldAttrEntity fieldAttrEntity, JSONObject jsonObject, List<List<SummaryDataPoJo>> stockFlowBillList) {
        List<SummaryDataPoJo> summaryDataPoJoList = new ArrayList<>();
        stockFlowBillList.add(summaryDataPoJoList);
        List<FieldAttrEntity> subExplainList = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), FieldAttrEntity.class);
        String parentName = fieldAttrEntity.getAttrName();
        subExplainList.forEach(item -> {
            // 去掉单位成本
            if (!Objects.equals(item.getAttr(), "num_2")) {
                SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo(item.getAttr(),parentName + item.getAttrName(),item.getFieldType(), Collections.singletonList(jsonObject.get(item.getAttr())));
                summaryDataPoJoList.add(summaryDataPoJo);
            }
        });
    }

    private void setProductSerialFlowList(FieldAttrEntity fieldAttrEntity, String status, List<List<SummaryDataPoJo>> productSerialList) {
        List<SummaryDataPoJo> summaryDataPoJoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(productSerialList)) {
            summaryDataPoJoList = productSerialList.get(0);
        } else {
            productSerialList.add(summaryDataPoJoList);
        }
        SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo(fieldAttrEntity.getAttr(), fieldAttrEntity.getAttrName(), fieldAttrEntity.getFieldType(), Collections.singletonList(status));
        summaryDataPoJoList.add(summaryDataPoJo);
    }
    /**
     * 设置一些特殊的筛选字段
     * 比如：产品列表的‘分类’字段
     * 前端传值的时候放在conditions中 后端需要将其放入commonFilter中
     *
     * @param formDataListDTO 列表查询入参
     * @author GuoJun.HU
     * @since V1.0
     * @return
     * @date 2019/4/16 20:28
     */
    private void setSpecialSearchAttr(FormDataListDTO formDataListDTO) {
        JSONObject commonFilter = formDataListDTO.getCommonFilter() == null ? new JSONObject(): formDataListDTO.getCommonFilter();
        List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
        for (Iterator<ConditionsEntityExt> iterator = conditionsEntityExtList.iterator(); iterator.hasNext();) {
            ConditionsEntityExt conditionsEntityExt = iterator.next();
            List<Object> values = conditionsEntityExt.getValue();
            if (Objects.equals(conditionsEntityExt.getAttr(), BusinessConstant.WARNING_TYPE)) {
                if (Objects.nonNull(values) && !values.isEmpty()) {
                    commonFilter.put(BusinessConstant.WARNING_TYPE, values.get(0));
                }
                iterator.remove();
            } else if (Objects.equals(conditionsEntityExt.getAttr(), BusinessConstant.GUARANTEE_STATUS)) {
                if (Objects.nonNull(values) && !values.isEmpty()) {
                    commonFilter.put(BusinessConstant.GUARANTEE_STATUS, values.get(0));
                }
                iterator.remove();
            }
        }
        if (commonFilter.containsKey("warehouseId")) {
            Object value = commonFilter.get("warehouseId");
            conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.WAREHOUSE.getAttr(),"",ProductEnum.WAREHOUSE.getFieldType(),ConditionEnum.INCLUDE.getSymbol(),Collections.singletonList(value)));
        }
        formDataListDTO.setCommonFilter(commonFilter);
    }

    /**
     * 库存查询获取分仓库存信息
     *
     * @param formDataItem  产品数据
     * @author GuoJun.HU
     * @since V1.0
     * @return List
     * @date 2019/4/3 13:40
     */
    private JSONArray getProductWarehouseInfo(PaasFormDataEntityExt formDataItem) throws XbbException {
        JSONObject childJsonObject = formDataItem.getData().getJSONObject(ListOptionEnum.MULTI_SPEC.getAttr());
        JSONArray jsonArray = childJsonObject.getJSONArray("value") == null ? new JSONArray() : childJsonObject.getJSONArray("value");
        Double totalStock = 0D;
        Double totalCost = 0D;
        boolean isCostVisible = true;
        boolean isStockVisible = true;
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            if (!Objects.equals(jsonObject.get("stock"), BasicConstant.NULL_SHOW_STR) && !Objects.equals(jsonObject.get("cost"), BasicConstant.NULL_SHOW_STR)) {
                Double stock = jsonObject.getDouble("stock");
                Double cost = jsonObject.getDouble("cost");
                totalCost = Arith.add(totalCost, Arith.mul(stock, cost));
                totalStock = Arith.add(totalStock, stock);
                if (Objects.equals(stock, 0D)) {
                    jsonObject.put("cost", BasicConstant.NULL_SHOW_STR);
                    jsonObject.put("costTotal", BasicConstant.NULL_SHOW_STR);
                }
            } else if (Objects.equals(jsonObject.get("cost"), BasicConstant.NULL_SHOW_STR) && !Objects.equals(jsonObject.get("stock"), BasicConstant.NULL_SHOW_STR)) {
                Double stock = jsonObject.getDouble("stock");
                totalStock = Arith.add(totalStock, stock);
                isCostVisible = false;
            } else if (!Objects.equals(jsonObject.get("cost"), BasicConstant.NULL_SHOW_STR)) {
                isStockVisible = false;
            } else {
                isStockVisible = false;
                isCostVisible = false;
            }
        }
        JSONObject warehouseItemObj = new JSONObject();
        warehouseItemObj.put("warehouseName", I18nMessageUtil.getMessage(I18nStringConstant.MAIN_WAREHOUSE));
        if (isCostVisible && isStockVisible) {
            warehouseItemObj.put("stock", totalStock);
            warehouseItemObj.put("cost", Objects.equals(totalStock,0D) ? BasicConstant.NULL_SHOW_STR : Arith.div(totalCost, totalStock));
            warehouseItemObj.put("costTotal", Objects.equals(totalStock,0D) ? BasicConstant.NULL_SHOW_STR : totalCost);
        } else if (!isCostVisible && isStockVisible) {
            warehouseItemObj.put("cost", BasicConstant.NULL_SHOW_STR);
            warehouseItemObj.put("stock", totalStock);
            warehouseItemObj.put("costTotal", BasicConstant.NULL_SHOW_STR);
        } else if (isCostVisible) {
            warehouseItemObj.put("cost", formDataItem.getData().get(ProductEnum.COST.getAttr()));
            warehouseItemObj.put("stock", BasicConstant.NULL_SHOW_STR);
            warehouseItemObj.put("costTotal", BasicConstant.NULL_SHOW_STR);
        } else {
            warehouseItemObj.put("cost", BasicConstant.NULL_SHOW_STR);
            warehouseItemObj.put("stock", BasicConstant.NULL_SHOW_STR);
            warehouseItemObj.put("costTotal", BasicConstant.NULL_SHOW_STR);
        }
        jsonArray.add(0, warehouseItemObj);
        formDataItem.getData().put(ProductEnum.STOCK.getAttr(),totalStock);
        return jsonArray;
    }
    /**
     * 手机首页指标穿透
     * @param resultThroughDTO
     * @return
     * @throws XbbException
     */
    @Override
    public ListAppVO customIndexMobileThrough(ResultThroughDTO resultThroughDTO)throws  XbbException{
        FormDataListDTO formDataListDTO = commonAssmblieListDTO(resultThroughDTO);
        //处理特殊filter的value
        conditionValueSpecialProcess(formDataListDTO);
        Integer businessType =  ListBusinessTypeEnum.getBusinessType(formDataListDTO.getSubBusinessType());
        if(businessType!=null) {
            formDataListDTO.setBusinessType(businessType);
        }
        return commonMobileAssmblieVO(formDataListDTO);
    }

    /**
     * 首页指标穿透
     * @param resultThroughDTO
     * @author yuqian
     * @date 2019/5/7 10:35
     * @return
     */
    @Override
    public  IndexThroughDTO customIndexThrough(ResultThroughDTO resultThroughDTO)throws XbbException {
        FormDataListDTO formDataListDTO = formDataListAssemble(resultThroughDTO);
        // 标记是从穿透过来的
        formDataListDTO.setFromThrough(true);

        IndexThroughDTO indexThroughDTO = new IndexThroughDTO();
        if(Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(),formDataListDTO.getSubBusinessType())){
            WorkOrderDataEsListVO workOrderDataEsListVO = workOrderFormDataService.normalList(formDataListDTO);
            showCustomIndexThroughResult(workOrderDataEsListVO,formDataListDTO.getSaasMark(),indexThroughDTO);
            //处理返回无businessType问题
            indexThroughDTO.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
        }else {
            PaasFormDataEsListVO formDataListVO = commonChooseBusinessThrough(formDataListDTO);
            showCustomIndexThroughResult(formDataListVO,formDataListDTO.getSaasMark(),indexThroughDTO);
        }
        // 是否有导出权限
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(formDataListDTO.getBusinessType());
        determineImportPermission(resultThroughDTO.getLoginUser(), xbbRefTypeEnum, indexThroughDTO);
        return indexThroughDTO;
    }
    /**
     * 判断穿透过去的数据是否支持导出
     * @param loginUser
     * @param xbbRefTypeEnum
     * @param indexThroughDTO
     */
    private void determineImportPermission(UserVO loginUser, XbbRefTypeEnum xbbRefTypeEnum, IndexThroughDTO indexThroughDTO) {
        indexThroughDTO.setShowExport(BasicConstant.ONE);
        ExportProPermissionAliasEnum exportProPermissionAliasEnum = ExportProPermissionAliasEnum.getByCode(xbbRefTypeEnum.getCode());
        if (Objects.nonNull(exportProPermissionAliasEnum)) {
            Set<String> permSet = loginUser.getPermSet();
            String alias = exportProPermissionAliasEnum.getAlias();
            if (!permSet.contains(alias) && !Objects.equals(alias, StringConstant.POSITIVE_NUMBER)) {
                indexThroughDTO.setShowExport(BasicConstant.ZERO);
            }
        }
    }

   public void showCustomIndexThroughResult(Object object,Integer saasMark,IndexThroughDTO indexThroughDTO){
        transferPojoToCommonDTO(object,indexThroughDTO);
        List<FieldAttrEntity> headList = indexThroughDTO.getHeadList();
        List<IndexThroughPojo> indexThroughPojoList = indexThroughDTO.getIndexThroughPojoList();
        Iterator<FieldAttrEntity> iterator = headList.iterator();
        if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
           if(CollectionsUtil.isNotEmpty(indexThroughPojoList)) {
               for (IndexThroughPojo indexThroughPojo : indexThroughPojoList) {
                   JSONObject jsonObject = indexThroughPojo.getData();
                   JSONObject valueObject = jsonObject.getJSONObject(ListOptionEnum.OPTION.getAttr());
                   JSONArray jsonArray = valueObject.getJSONArray("value");
                   Iterator it = jsonArray.iterator();
                   while (it.hasNext()) {
                       JSONObject optionJson = JSONObject.parseObject(it.next().toString());
                       if (!ListOptionTabEnum.VIEW.getAttr().equals(optionJson.getString("attr"))) {
                           it.remove();
                       }
                   }
                   valueObject.put("value", jsonArray);
               }
           }
       }
       while (iterator.hasNext()) {
           FieldAttrEntity fieldAttrEntity = iterator.next();
           Integer type = fieldAttrEntity.getFieldType();
           FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(type);
           if (FieldTypeEnum.OPTION.equals(fieldTypeEnum)) {
               if (SaasMarkEnum.SAAS.getCode().equals(saasMark)) {
                   iterator.remove();
               }
           } else if (FieldTypeEnum.REMIND.equals(fieldTypeEnum)
                   || FieldTypeEnum.FOCUS.equals(fieldTypeEnum)
                   || FieldTypeEnum.CALL.equals(fieldTypeEnum)
                   || FieldTypeEnum.SUB_FORM.equals(fieldTypeEnum)
                   || FieldTypeEnum.FLOW.equals(fieldTypeEnum)
                   || FieldTypeEnum.CONTACT_NUMBER.equals(fieldTypeEnum)
                   || FieldTypeEnum.STOCK_SEARCH.equals(fieldTypeEnum)
                   || FieldTypeEnum.SELECT_PRODUCT.equals(fieldTypeEnum)) {
               iterator.remove();
           }
       }
   }

   public void transferPojoToCommonDTO(Object object,IndexThroughDTO indexThroughDTO){
       if(object instanceof PaasFormDataEsListVO){
           PaasFormDataEsListVO formDataListVO = (PaasFormDataEsListVO) object;
           BeanUtil.copyProperties(formDataListVO,indexThroughDTO);
           List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
           String jsonArray = JSONArray.toJSONString(paasFormDataESList);
           List<IndexThroughPojo> indexThroughDTOList = JSONArray.parseArray(jsonArray,IndexThroughPojo.class);
           indexThroughDTO.setIndexThroughPojoList(indexThroughDTOList);
       }else if(object instanceof WorkOrderDataEsListVO){
           WorkOrderDataEsListVO workOrderDataEsListVO = (WorkOrderDataEsListVO) object;
           BeanUtil.copyProperties(workOrderDataEsListVO,indexThroughDTO);
           List<WorkOrderEntityExt> paasFormDataESList = workOrderDataEsListVO.getPaasFormDataESList();
           String jsonArray = JSONArray.toJSONString(paasFormDataESList);
           List<IndexThroughPojo> indexThroughDTOList = JSONArray.parseArray(jsonArray,IndexThroughPojo.class);
           indexThroughDTO.setIndexThroughPojoList(indexThroughDTOList);
       }
   }

    @Override
    public IndexCommunivateVo customerCommunicateIndexThrough(ResultThroughDTO resultThroughDTO)throws XbbException {
        FormDataListDTO formDataListDTO = formDataListAssemble(resultThroughDTO);
        return customCommuntcateBusinessThrough(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO communicatePlanList4Export(CommunicatePlanExportDTO communicatePlanExportDTO) throws XbbException {
        CommunicatePlanDTO communicatePlanDTO = new CommunicatePlanDTO();
        BeanUtil.copyProperties(communicatePlanExportDTO, communicatePlanDTO);
        List<PaasFormDataEntityExt> planList = new ArrayList<>();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        try{
            List<ConditionsEntityExt> conditionsEntityExtList = communicatePlanService.setConditionList(communicatePlanDTO);
            // 拼接父子文档参数条件
            communicatePlanService.setTeamCondition(communicatePlanDTO, conditionsEntityExtList);
            JSONArray planDateArr = communicatePlanExportDTO.getPlanDateArr();
            if (Objects.nonNull(planDateArr) && !planDateArr.isEmpty()) {
                conditionsEntityExtList.add(EsUtil.packageContions(
                        CommunicatePlanEnum.COMMUNICATE_TIME.getAttr(), BasicHelper.timeStrToValueList(planDateArr),
                        ConditionEnum.RANGE, CommunicatePlanEnum.COMMUNICATE_TIME.getFieldType()));
            }
            EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,null,communicatePlanExportDTO.getCorpid(),XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
            boolQueryBuilder.filter(termQuery("corpid.keyword",  communicatePlanExportDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            planList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_COMMUNICATE_PLAN, boolQueryBuilder, PaasFormDataEntityExt.class, null);
            if (CollectionsUtil.isEmpty(planList)) {
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235005);
            }
        }catch (Exception e){
            LOG.error("访客计划es查询-------",e);
        }

        //用户id的list
        List<Long> customerIdIn = new ArrayList<>();
        for (PaasFormDataEntityExt paasFormDataEntityExt : planList) {
            JSONObject data = paasFormDataEntityExt.getData();
            Long customerId = FastJsonHelper.getLongFromFormData(data, CommunicatePlanEnum.LINK_CUSTOMER.getAttr());
            if (Objects.nonNull(customerId)) {
                customerIdIn.add(customerId);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("corpid",communicatePlanDTO.getCorpid());
        map.put("customerIdIn", customerIdIn);
        map.put("del", DelEnum.NORMAL.getDel());
        //客户对应的团队
        List<CustomerUserEntity> customerUserEntityList = customerUserDao.findEntitys(map);

        //解析planList中dataId
        List<Long> dataIdList = planList.stream().map(PaasFormDataEntityExt::getDataId).collect(Collectors.toList());
        Map<String,Object> parme = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        parme.put("corpid",communicatePlanDTO.getCorpid());
        parme.put("dataIdIn",dataIdList);
        List<CommunicatePlanUserEntity> planUserModelList = communicatePlanUserModel.findEntitys(parme);

        Map<Long, List<CustomerUserEntity>> customerUserMap = customerUserEntityList.stream()
                .collect(Collectors.groupingBy(CustomerUserEntity::getDataId));
        Map<Long, JSONObject> planMap = planList.stream().collect(Collectors.toMap(PaasFormDataEntityExt::getDataId, PaasFormDataEntityExt::getData));
        Iterator<CommunicatePlanUserEntity> iterator = planUserModelList.iterator();
        while (iterator.hasNext()){
            CommunicatePlanUserEntity communicatePlanUserEntity = iterator.next();
            JSONObject data = planMap.get(communicatePlanUserEntity.getDataId());
            if (Objects.isNull(data)) {
                continue;
            }
            Long customerId = FastJsonHelper.getLongFromFormData(data, CommunicatePlanEnum.LINK_CUSTOMER.getAttr());
            List<CustomerUserEntity> customerUserList = customerUserMap.get(customerId);
            //得到执行人集合
            JSONArray executorList = FastJsonHelper.getJsonArrFromFormData(data, CommunicatePlanEnum.EXECUTOR.getAttr());
            //协同人+负责人
            List<String> totalList = CollectionsUtil.isNotEmpty(executorList) ? executorList.toJavaList(String.class) : new ArrayList<>();
            List<String> chargeName = new ArrayList<>();
            if(CollectionsUtil.isNotEmpty(customerUserList)){
                if (totalList.contains("0")){
                    List<String> name = customerUserList.stream().filter(customerUserEntity -> customerUserEntity.getIsMain() == 1)
                            .map(CustomerUserEntity::getUserName).collect(Collectors.toList());
                    chargeName.addAll(name);
                }
                if (totalList.contains("1")){
                    List<String> name = customerUserList.stream().filter(customerUserEntity -> customerUserEntity.getIsMain() != 1)
                            .map(CustomerUserEntity::getUserName).collect(Collectors.toList());
                    chargeName.addAll(name);
                }
            }
            JSONArray array= FastJsonHelper.getJsonArrFromFormData(data, CommunicatePlanEnum.EXECUTOR_LINKED_TEXT.getAttr());
            if (CollectionsUtil.isNotEmpty(array)){
                List<String> list = array.toJavaList(String.class);
                if (list.contains(communicatePlanUserEntity.getUserId())
                        && !chargeName.contains(communicatePlanUserEntity.getUserName())){
                    iterator.remove();
                }
            }
        }
        //key为dataId ,value为userName
        Map<Long, String> planUserModelMap = planUserModelList.stream().collect(Collectors.toMap(CommunicatePlanUserEntity::getDataId,
                CommunicatePlanUserEntity::getUserName,
                (value1, value2) -> {
                    return value1 + " " + value2;
                }));

        for (Map.Entry<Long, JSONObject> entry : planMap.entrySet()) {
            JSONObject value = entry.getValue();
            value.put(CommunicatePlanEnum.EXECUTOR.getAttr(),new ArrayList<>());
        }
        for (Map.Entry<Long, String> entry : planUserModelMap.entrySet()) {
            JSONObject jsonObject = planMap.get(entry.getKey());
            List<String> list = new ArrayList<>();
            list.add(entry.getValue());
            jsonObject.put(CommunicatePlanEnum.EXECUTOR.getAttr(),list);
        }
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        paasFormDataEsListVO.setPaasFormDataESList(planList);
        PaasFormExplainEntity planExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), communicatePlanExportDTO.getCorpid());
        if (Objects.isNull(planExplain)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(planExplain.getExplains(), null);
        paasFormDataEsListVO.setExplainMap(explainMap);
        return paasFormDataEsListVO;
    }

    @Override
    public ListAppVO getWaitPurchaseList(FormDataListDTO formDataListDTO, PaasFormDataEsListVO paasFormDataEsListVO) throws XbbException {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(formDataListDTO.getBusinessType());
        switch (redundantTemplateTypeEnum) {
            case CONTRACT:
                return contractService.formatWaitPurchaseContract(formDataListDTO, paasFormDataEsListVO);
            case PRODUCT:
                return productService.formatWaitPurchaseProduct(formDataListDTO, paasFormDataEsListVO);
            default:
                throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
    }

    @Override
    public ListAppVO getMobileSmartReplenishment(FormDataListDTO formDataListDTO, PaasFormDataEsListVO paasFormDataEsListVO) throws XbbException {
        List<AppListPojo> appListPojos = new ArrayList<>();
        String corpid = formDataListDTO.getCorpid();
        ListAppVO listAppVO = new ListAppVO();
        List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();
        List<FieldAttrEntity> headList = paasFormDataEsListVO.getHeadList();
        listAppVO.setHeadList(headList);
        if (CollectionsUtil.isNotEmpty(paasFormDataESList)) {
            for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                AppListPojo appListPojo = new AppListPojo();
                Long productId = paasFormDataEntityExt.getDataId();
                JSONObject data = paasFormDataEntityExt.getData();
                appListPojo.setId(productId);
                appListPojo.setName(data.getString(ProductEnum.NAME.getAttr()));
                JSONArray explains = new JSONArray();
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.SPECIFICATION.getAttrName(), data.get(ProductEnum.SPECIFICATION.getAttr())));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, "产品单位", data.get(ProductEnum.UNIT.getAttr())));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, "未出库数量", data.getDouble("waitOutstockNum")));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, "库存数量", data.get(ProductEnum.STOCK.getAttr())));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, "建议采购量", data.getDouble("advisePurchaseNum")));


                appListPojo.setExplains(explains);
                JSONObject others = new JSONObject();
                JSONArray productImgs = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ProductEnum.PRODUCT_IMGS.getAttr(), new JSONArray());
                String productImg = productImgs.isEmpty() ? null : productImgs.get(0).toString();
                others.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), productImg);
                appListPojo.setOthers(others);
                appListPojo.setData(data);
                appListPojos.add(appListPojo);
            }
        }

        listAppVO.setList(appListPojos);
        listAppVO.setTotalCount(paasFormDataEsListVO.getPageHelper().getRowsCount());
        return listAppVO;
    }


    /**
     * 获取移动端待生产列表
     *
     * @param formDataListDTO      列表页请求参数
     * @param paasFormDataEsListVO 查询数据回参
     * @throws XbbException
     * @author youli.chen
     * @date 2019-05-31 10:45
     */
    @Override
    public ListAppVO getWaitProduceList(FormDataListDTO formDataListDTO, PaasFormDataEsListVO paasFormDataEsListVO) throws XbbException {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(formDataListDTO.getBusinessType());
        switch (redundantTemplateTypeEnum) {
            case CONTRACT:
                return contractService.formatWaitContract(formDataListDTO, paasFormDataEsListVO);
            case PRODUCT:
                return productService.formatWaitProduct(formDataListDTO, paasFormDataEsListVO);
            default:
                throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
    }

    /**
     * 获取移动端待入库列表
     *
     * @param formDataListDTO      列表页请求参数
     * @param paasFormDataEsListVO 查询数据回参
     * @throws XbbException
     * @author youli.chen
     * @date 2019-05-31 10:45
     */
    @Override
    public ListAppVO formatWaitContractInstock(FormDataListDTO formDataListDTO, PaasFormDataEsListVO paasFormDataEsListVO) throws XbbException {
        ListAppVO listAppVO = new ListAppVO();
        if(Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE.getCode())){
            listAppVO = contractService.formatWaitPurchaseInstock(formDataListDTO, paasFormDataEsListVO);
        }else if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            listAppVO = contractService.formatWaitProductInstock(formDataListDTO, paasFormDataEsListVO);
        }
        return listAppVO;
    }

    /**
     * 获取移动端待出库列表
     *
     * @param formDataListDTO      列表页请求参数
     * @param paasFormDataEsListVO 查询数据回参
     * @throws XbbException
     * @author youli.chen
     * @date 2019-05-31 10:45
     */
    @Override
    public ListAppVO formatWaitContractOutstock(FormDataListDTO formDataListDTO, PaasFormDataEsListVO paasFormDataEsListVO) throws XbbException {
        return contractService.formatWaitContractOutstock(formDataListDTO, paasFormDataEsListVO);
    }


    /**
     * 组装formDataListDTO 用作查询入参
     * @param resultThroughDTO 入参
     * @throws XbbException error
     */
    @Override
    public FormDataListDTO formDataListAssemble(ResultThroughDTO resultThroughDTO) throws XbbException {
        FormDataListDTO formDataListDTO = commonAssmblieListDTO(resultThroughDTO);
        //处理特殊filter的value
        conditionValueSpecialProcess(formDataListDTO);
        Integer businessType =  ListBusinessTypeEnum.getBusinessType(formDataListDTO.getSubBusinessType());
        //工单没有菜单结构 特殊处理
        if(Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(),formDataListDTO.getSubBusinessType())){
            businessType = XbbRefTypeEnum.WORK_ORDER.getCode();
        }
        formDataListDTO.setBusinessType(businessType);
        TransmittableThreadLocalUtil.setValue(formDataListDTO.getSaasMark(), formDataListDTO.getBusinessType(), formDataListDTO.getMenuId(), formDataListDTO.getDistributorMark());
        return formDataListDTO;
    }

    /**
     * PC和手机 公共封装FormDataListDto 方法
     * @param resultThroughDTO
     * @Author yuqian
     * @return formDataListDTO
     */
    private FormDataListDTO commonAssmblieListDTO(ResultThroughDTO resultThroughDTO) throws XbbException{
        ChartEntity chartEntity;
        if (resultThroughDTO.getStatisticsType() != null && Objects.equals(resultThroughDTO.getStatisticsType(), StatisticsTypeEnum.SYSTEM_STATISTIC.getCode())) {
            chartEntity = chartModel.getByKey(resultThroughDTO.getId(),resultThroughDTO.getCorpid());
        } else {
            chartEntity = chartCustomModel.getByKey(resultThroughDTO.getId(),resultThroughDTO.getCorpid());
        }
        UserEntity userEntity = BeanUtil.copyProperties(resultThroughDTO.getLoginUser(), UserEntity.class, false);
        if(chartEntity==null){
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224005);
        }
        JSONObject driverSourcesObject = chartEntity.getDriverSources();
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(resultThroughDTO,formDataListDTO);
        formDataListDTO.setAppId(driverSourcesObject.getLong("appId"));
        formDataListDTO.setFormId(driverSourcesObject.getLong("formId"));
        formDataListDTO.setSaasMark(driverSourcesObject.getInteger("saasMark"));
        formDataListDTO.setSubBusinessType(driverSourcesObject.getInteger("businessType"));
        formDataListDTO.setMenuId(driverSourcesObject.getLong("menuId"));
        TransmittableThreadLocalUtil.setValue(formDataListDTO.getSaasMark(), formDataListDTO.getBusinessType(), formDataListDTO.getMenuId(), formDataListDTO.getDistributorMark());
        JSONArray jsonArray = chartEntity.getFilter();
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()) {
            JSONObject filterJson = (JSONObject)iterator.next();
            String saasAttr = filterJson.getString("saasAttr");
            //是否公海 提前设置subBusinessType
            // 是否公海 和 是否归档 特殊处理
            if (Objects.equals(saasAttr, CustomerManagementEnum.IS_PUBLIC.getSaasAttr())){
                JSONArray valueArray = filterJson.getJSONArray("value");
                if(valueArray!=null) {
                    if(Objects.equals(valueArray.get(0),BasicConstant.ONE)){
                        if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                            formDataListDTO.setSubBusinessType(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode());
                        } else if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.CLUE.getCode())) {
                            formDataListDTO.setSubBusinessType(XbbRefTypeEnum.CLUE_PUBLIC.getCode());
                        }
                        //并且移除掉是否公海的条件,在调用公海池列表接口会自动装入,避免重复
                        iterator.remove();
                    }
                }
            }
            if (Objects.equals(saasAttr, CustomerManagementEnum.IS_PUBLIC.getSaasAttr()) || Objects.equals(saasAttr, CustomerManagementEnum.IS_ARCHIVED.getSaasAttr())) {
                filterJson.put("fieldType",FieldTypeEnum.STAR.getType());
            }
        }
        if(Objects.equals(driverSourcesObject.getInteger("businessType"),XbbRefTypeEnum.WORK_ORDER.getCode())){
            formDataListDTO.setDefaultGroup(BasicConstant.ONE);
            formDataListDTO.setListGroupId(Long.valueOf(BasicConstant.ZERO));
        }
        List<ConditionsEntityExt> conditionsEntityExts = JSONArray.parseArray(jsonArray.toJSONString(),ConditionsEntityExt.class);
        //2019-9-26 上线 TODO 先处理 后续和上面代码合并整理
        for (int i = 0; i < conditionsEntityExts.size(); i++) {
            ConditionsEntityExt condition = conditionsEntityExts.get(i);
            EsUtil.subFormParseValue(condition);
            // 动态时间处理
            if (Objects.equals(condition.getSymbol(), ConditionEnum.NORMAL.getSymbol())
                    || Objects.equals(condition.getSymbol(), ConditionEnum.CUSTOM.getSymbol())) {
                JSONObject conditionObj = JSON.parseObject(JSON.toJSONString(condition, SerializerFeature.DisableCircularReferenceDetect));
                EsUtil.handleNormalOrCustomFilter(chartEntity, conditionObj);
                condition = JSON.toJavaObject(conditionObj, ConditionsEntityExt.class);
                conditionsEntityExts.set(i, condition);
            }
        }
        JSONObject belongJson = chartEntity.getBelongAttr();
        JSONObject timeJson = chartEntity.getTimeAttr();
        ConditionsEntityExt belongCondition = JSONObject.parseObject(belongJson.toJSONString(),ConditionsEntityExt.class);
        ConditionsEntityExt timeCondition = JSONObject.parseObject(timeJson.toJSONString(),ConditionsEntityExt.class);
        if(belongCondition!=null) {
            /*--------处理dataPermission--------*/
            //默认走组织架构权限，有可能不是负责人
            int dataPermission = userModel.getDataPermission(userEntity, true);
            List<String> userIdIn = new ArrayList<>();
            int isShowLeave = 1;
            /*--------处理userIdIn--------*/
            if(resultThroughDTO.getPerformancePk()){
                //如果为业绩目标，判断是否需要过滤离职人员
                isShowLeave = commonHelp.isShowPerformLeave(resultThroughDTO.getCorpid()) ? isShowLeave : 0;
                userIdIn = chartDtoHelp.getUserIdIn(userEntity, dataPermission, resultThroughDTO.getCheckedDepId(), resultThroughDTO.getCheckedUserId(),resultThroughDTO.getCheckedId(),new ChartResultBaseDTO(), isShowLeave);
            } else if(resultThroughDTO.getCheckedDepId()==null || !BasicConstant.ONE.equals(resultThroughDTO.getCheckedDepId().intValue())){
                userIdIn = chartDtoHelp.getUserIdIn(userEntity, dataPermission, resultThroughDTO.getCheckedDepId(), resultThroughDTO.getCheckedUserId(),resultThroughDTO.getCheckedId(),new ChartResultBaseDTO(), isShowLeave);
            }
            // 自定义pk按人穿透
            if (Objects.equals(chartEntity.getChartType(), ChartTypeEnum.PK_CUSTOM.getCode())) {
                userIdIn = Arrays.asList(resultThroughDTO.getCheckedUserId());
            }
            List<Object> list = new ArrayList<>();
            if(userIdIn.size()>1) {
                belongCondition.setSymbol(ConditionEnum.IN.getSymbol());
            }else {
                belongCondition.setSymbol(ConditionEnum.EQUAL.getSymbol());
            }
            list.addAll(userIdIn);
            belongCondition.setValue(list);
            conditionsEntityExts.add(belongCondition);
        }
        if(timeCondition!=null){
            timeCondition.setSymbol(ConditionEnum.RANGE.getSymbol());
            if(resultThroughDTO.getStartTime() != null && resultThroughDTO.getEndTime() != null){
                List<Object> list = new ArrayList<>();
                list.add(resultThroughDTO.getStartTime());
                list.add(resultThroughDTO.getEndTime());
                timeCondition.setValue(list);
                conditionsEntityExts.add(timeCondition);
            }
        }
        formDataListDTO.setConditions(conditionsEntityExts);
        return formDataListDTO;
    }

    /**
     * 手机 公共封装ListAppVO 方法
     * @param formDataListDTO
     * @Author yuqian
     * @return
     */
    public ListAppVO commonMobileAssmblieVO(FormDataListDTO formDataListDTO)throws XbbException{
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(formDataListDTO.getSubBusinessType());
        TransmittableThreadLocalUtil.setValue(formDataListDTO.getSaasMark(), formDataListDTO.getSubBusinessType(), formDataListDTO.getMenuId(), formDataListDTO.getDistributorMark());
        ListAppVO listAppVO = new ListAppVO();
        PaasFormDataEsListVO  paasFormDataEsListVO = null;
        List<PaasFormDataEntityExt> esEntities = null;
        Integer totalCount = null;
        switch (xbbRefTypeEnum){
            case CUSTOMER:
            case CUSTOMER_MANAGEMENT:
            case CUSTOMER_PUBLIC:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    if(XbbRefTypeEnum.CUSTOMER_PUBLIC.equals(xbbRefTypeEnum)){
                        esEntities.forEach(item -> {
                            item.getData().put(CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ONE);
                        });
                    }
                   totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = customerService.formatCustomerAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case CONTRACT:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = contractService.formatContractAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case REFUND:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = refundService.formatRefundAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case SALES_OPPORTUNITY:
            case ALL_OPPORTUNITY:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = opportunityService.formatOpportunityAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case CONTACT:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if ( totalCount != null && totalCount != 0) {
                    listAppVO = contactService.formatContactAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case PAYMENT:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = paymentService.formatPaymentAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case PAYMENT_SHEET:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = paymentSheetService.formatPaymentSheetAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case PAY_SHEET:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = payPlanSheetService.formatPaySheetAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case INVOICE:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = invoiceService.formatInvoiceAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case PURCHASE_INVOICE:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO != null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    if(XbbRefTypeEnum.CLUE_PUBLIC.equals(xbbRefTypeEnum)){
                        esEntities.forEach(item -> {
                            item.getData().put(ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ONE);
                        });
                    }
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = purchaseInvoiceService.formatInvoiceAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case WORK_ORDER:
                WorkOrderDataEsListVO workOrderDataEsListVO = workOrderFormDataService.normalList(formDataListDTO);
                List<WorkOrderEntityExt> workOrderEntityExts = workOrderDataEsListVO.getPaasFormDataESList();
                totalCount = workOrderDataEsListVO.getPageHelper().getRowsCount();
                listAppVO = new ListAppVO();
                if (totalCount != null && totalCount != 0) {
                    listAppVO = workOrderService.formatWorkOrderAppList(formDataListDTO, workOrderEntityExts, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(workOrderDataEsListVO));
                break;
            case QUOTATION:
                paasFormDataEsListVO = quotationList(formDataListDTO);
                if(paasFormDataEsListVO !=null) {
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = quotationService.formatQuotationAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission( getAppListAddPermission(paasFormDataEsListVO));
                break;
            case PAY_PLAN:
            case SUPPLIER:
            case SUPPLIER_CONTACT:
            case PURCHASE:
            case RETURNED_PURCHASE:
            case ASSEMBLE:
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case TRANSFER:
            case INVENTORY:
            case WAREHOUSE:
            case BOM_BILL:
            case PRODUCTION_ORDER:
                listAppVO = appList(formDataListDTO);
                break;
            case PRODUCT:
                formDataListDTO.setThrough(true);
                listAppVO = appList(formDataListDTO);
                break;
            case STOCK_SEARCH:
                listAppVO = appList(formDataListDTO);
                ListAppExtVO listAppExtVO = new ListAppExtVO();
                BeanUtil.copyProperties(listAppVO, listAppExtVO);
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.INVENTORY.getCode(), formDataListDTO.getCorpid());
                UserFormPermissionVO userFormPermissionVO = userService.getUserFormPermissionInternal(formDataListDTO.getCorpid(),
                        formDataListDTO.getUserId(), paasFormEntityExt.getAppId(), paasFormEntityExt.getMenuId());
                PermissionTermsPojo permissionTerms = userFormPermissionVO.getFormPermission().getPermission();
                boolean inventoryAddPermission = userFormPermissionVO.getIsAdminOrBoss() || Objects.equals(permissionTerms.getCreate(), 1);
                JSONObject inventoryOption = new JSONObject();
                inventoryOption.put("addPermission", inventoryAddPermission);
                inventoryOption.put("appId", paasFormEntityExt.getAppId());
                inventoryOption.put("menuId", paasFormEntityExt.getMenuId());
                inventoryOption.put("formId", paasFormEntityExt.getId());
                inventoryOption.put("businessType", XbbRefTypeEnum.INVENTORY.getCode());
                listAppExtVO.setExtraOption(inventoryOption);
                break;
            case MARKET_ACTIVITY:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO != null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = marketActivityService.formatMarketActivityAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case CLUE:
            case CLUE_PUBLIC:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO != null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = clueService.formatClueAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case ONLINE_PAYMENT_FLOW:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = onlinePaymentFlowService.formatOnlinePaymentFlowAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            case FUND_TRANSFER:
                paasFormDataEsListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
                if(paasFormDataEsListVO !=null){
                    esEntities = paasFormDataEsListVO.getPaasFormDataESList();
                    totalCount = paasFormDataEsListVO.getPageHelper().getRowsCount();
                }
                if (totalCount != null && totalCount != 0) {
                    listAppVO = fundTransferService.formatFundTransferAppList(formDataListDTO, esEntities, totalCount);
                } else {
                    listAppVO.setList(new ArrayList<>());
                    listAppVO.setTotalCount(0);
                }
                listAppVO.setAddPermission(getAppListAddPermission(paasFormDataEsListVO));
                break;
            default:
                throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return listAppVO;
    }

    /**
     * 根据业务封装PaasFormDataEsListVO方法
     * @param formDataListDTO
     * @Author yuqian
     * @return
     */
    private PaasFormDataEsListVO commonChooseBusinessThrough(FormDataListDTO formDataListDTO) throws XbbException{
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(formDataListDTO.getSubBusinessType());
        Integer businessType = formDataListDTO.getBusinessType();
        PaasFormDataEsListVO formDataListVO;
        Integer customBusinessType = 0;
        if(SaasMarkEnum.PAAS.getCode().equals(formDataListDTO.getSaasMark())&&businessType.equals(customBusinessType)){
            formDataListVO = paasFormDataService.listByEs(formDataListDTO);
        }else {
            //报价单 历史版本特殊逻辑，自定义指标默认展示所有版本数据包含历史版本
            if (Objects.equals(XbbRefTypeEnum.QUOTATION, xbbRefTypeEnum)) {
                List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
                Iterator<ConditionsEntityExt> iterator = conditions.iterator();
                while (iterator.hasNext()){
                    ConditionsEntityExt e = iterator.next();
                    if (!Objects.equals(QuotationEnum.IS_NEW.getAttr(), e.getAttr()) || !Objects.equals(XbbRefTypeEnum.QUOTATION.getCode(), formDataListDTO.getSubBusinessType())) {
                        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                        conditionsEntityExt.setAttr(QuotationEnum.IS_NEW.getAttr());
                        conditionsEntityExt.setFieldType(QuotationEnum.IS_NEW.getFieldType());
                        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                        conditionsEntityExt.setHasEmpty(0);
                        conditionsEntityExt.setSort(QuotationEnum.IS_NEW.getSort());
                        List<Object> values = new ArrayList<>();
                        values.add(0);
                        values.add(1);
                        conditionsEntityExt.setValue(values);
                        conditions.add(conditionsEntityExt);
                        break;
                    }
                }
            }
            formDataListVO = commonBusinessTypeHandle(xbbRefTypeEnum,formDataListDTO);
        }
        return formDataListVO;
    }

    private PaasFormDataEsListVO commonBusinessTypeHandle(XbbRefTypeEnum xbbRefTypeEnum,FormDataListDTO formDataListDTO)throws XbbException{
        PaasFormDataEsListVO formDataListVO;
        switch (xbbRefTypeEnum){
            case CUSTOMER_MANAGEMENT:
            case CUSTOMER_PUBLIC:
                if(Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode())){
                   formDataListVO = publicCustomer(formDataListDTO);
                }else {
                    formDataListDTO.setPlatform(PlatFormEnum.DINGTALK.getValue());
                    formDataListVO = customerList(formDataListDTO);
                }
                break;
            case CONTRACT:
                formDataListDTO.setPlatform(PlatFormEnum.DINGTALK.getValue());
                formDataListVO = contractList(formDataListDTO);
                break;
            case CUSTOMER_COMMUNICATE:
                formDataListVO = customerCommunicateList(formDataListDTO);
                break;
            case REFUND:
                formDataListVO = refundList(formDataListDTO);
                break;
            case SALES_OPPORTUNITY:
                formDataListDTO.setSubBusinessType(XbbRefTypeEnum.ALL_OPPORTUNITY.getCode());
                formDataListVO = opportunityList(formDataListDTO);
                break;
            case CONTACT:
                formDataListVO = contactList(formDataListDTO);
                break;
            case PAYMENT:
                formDataListVO = paymentList(formDataListDTO);
                break;
            case PAY_PLAN:
                formDataListVO = payPlanList(formDataListDTO);
                break;
            case INVOICE:
                formDataListDTO.setDefaultGroup(BasicConstant.ONE);
                formDataListDTO.setListGroupId(Long.valueOf(ListGroupEnum.ALL.getCode()));
                formDataListVO = invoiceList(formDataListDTO);
                break;
            case PURCHASE_INVOICE:
                formDataListDTO.setDefaultGroup(BasicConstant.ONE);
                formDataListDTO.setListGroupId(Long.valueOf(ListGroupEnum.ALL.getCode()));
                formDataListVO = purchaseInvoiceList(formDataListDTO);
                break;
            case SUPPLIER:
                formDataListVO = supplierList(formDataListDTO);
                break;
            case SUPPLIER_CONTACT:
                formDataListVO = supplierContactList(formDataListDTO);
                break;
            case SUPPLIER_COMMUNICATE:
                formDataListVO = supplierCommunicateList(formDataListDTO);
                break;
            case PURCHASE:
                formDataListVO = purchaseList(formDataListDTO);
                break;
            case RETURNED_PURCHASE:
                formDataListVO = returnedPurchaseList(formDataListDTO);
                break;
            case ASSEMBLE:
                formDataListVO = assembleList(formDataListDTO);
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                formDataListVO = instockList(formDataListDTO);
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
                formDataListVO = outstockList(formDataListDTO);
                break;
            case TRANSFER:
                formDataListVO = transferList(formDataListDTO);
                break;
            case INVENTORY:
                formDataListVO = inventoryList(formDataListDTO);
                break;
            case WAREHOUSE:
                formDataListVO = warehouseList(formDataListDTO);
                break;
            case STOCK_SEARCH:
                formDataListVO = newProductStockList(formDataListDTO);
                break;
            case BOM_BILL:
                formDataListVO = bombillList(formDataListDTO);
                break;
            case PRODUCTION_ORDER:
                formDataListVO = productionOrderList(formDataListDTO);
                break;
            case PRODUCT:
                formDataListVO = productListSuperByIndex(formDataListDTO);
                break;
            case QUOTATION:
                formDataListVO =  quotationList(formDataListDTO);
                break;
            case PAYMENT_SHEET:
                formDataListVO = paymentSheetList(formDataListDTO);
                break;
            case PAY_SHEET:
                formDataListVO = paySheetList(formDataListDTO);
                break;
            case CLUE:
                formDataListVO = clueList(formDataListDTO);
                break;
            case CLUE_PUBLIC:
                formDataListVO = publicClue(formDataListDTO);
                break;
            case ONLINE_PAYMENT_FLOW:
                formDataListVO = onlinePaymentFlowList(formDataListDTO);
                break;
            case MARKET_ACTIVITY:
                formDataListVO = marketActivityList(formDataListDTO);
                break;
            case OTHER_INCOME:
                formDataListVO = otherIncomeList(formDataListDTO);
                break;
            case OTHER_EXPENSE:
                formDataListVO = otherExpenseList(formDataListDTO);
                break;
            case FUND_TRANSFER:
                formDataListVO = fundTransferList(formDataListDTO);
                break;
            case DISTRIBUTOR_ACCOUNT:
                formDataListVO = distributorAccountList(formDataListDTO);
                break;
            case COMPETITOR:
                formDataListVO = competitorList(formDataListDTO);
                break;
            case WORK_ORDER_V2:
            case SERVICE_PROJECT:
            case SLA_LOG:
            case RECEIPT_ORDER:
                try {
                    formDataListDTO.setBusinessType(xbbRefTypeEnum.getCode());
                    String str = workOrderV2CommonFeignClient.list(formDataListDTO, LocaleContextHolder.getLocale().toString());
                    XbbResponse  response = JSONObject.parseObject(str,XbbResponse.class);
                    if (!response.isSuccess()) {
                        throw new XbbException(response.getCode(), response.getMsg());
                    }
                    JSONObject result = (JSONObject) response.getResult();
                    formDataListVO = JSONObject.parseObject(result.toJSONString(), PaasFormDataEsListVO.class);
                } catch (Exception e) {
                    LOG.error("Work order v2 feign rpc fail",e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                break;
            default:
                throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        return formDataListVO;
    }
    /**
     * 跟进记录穿透业务
     * @param formDataListDTO
     * @Author yuqian
     * @return
     */
    private IndexCommunivateVo customCommuntcateBusinessThrough(FormDataListDTO formDataListDTO) throws XbbException{
        CommunicateVO communicateVO;
        if(formDataListDTO.getBusinessType().equals(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode())){
            communicateVO = customerCommunicateService.list(formDataListDTO);
        }else if(formDataListDTO.getBusinessType().equals(XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode())){
            communicateVO = supplierCommunicateService.list(formDataListDTO);
        }else {
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        IndexCommunivateVo indexCommunivateVo = new IndexCommunivateVo();
        if(communicateVO!=null) {
            BeanUtil.copyProperties(communicateVO, indexCommunivateVo);
            indexCommunivateVo.setFormId(formDataListDTO.getFormId());
            indexCommunivateVo.setAppId(formDataListDTO.getAppId());
            indexCommunivateVo.setMenuId(formDataListDTO.getMenuId());
            indexCommunivateVo.setBusinessType(formDataListDTO.getBusinessType());
            indexCommunivateVo.setSubBusinessType(formDataListDTO.getSubBusinessType());
            indexCommunivateVo.setSaasMark(formDataListDTO.getSaasMark());
            indexCommunivateVo.setShowExport(BasicConstant.ONE);
        }
        return indexCommunivateVo;
    }


    /**
     * 筛选条件特殊处理
     *
     * @param formDataListDTO
     */
    private void conditionValueSpecialProcess(FormDataListDTO formDataListDTO){
        List<ConditionsEntityExt> conditionsEntityExts = formDataListDTO.getConditions();
        if (CollectionsUtil.isNotEmpty(conditionsEntityExts)) {
            //列表地址查询方式改了 坑死我算了
            for (ConditionsEntityExt condition : conditionsEntityExts) {
                if(FieldTypeEnum.ADDRESS.equals(FieldTypeEnum.getFieldTypeEnum(condition.getFieldType()))) {
                    String[] attrs = condition.getAttr().split("\\.");
                    String attr = attrs[0];
                    if(StringUtil.isNotEmpty(attr)){
                        condition.setAttr(attr);
                    }
                }
            }
        }
    }

    /**
     * 设置产品，库存查询的特殊数据
     *
     * @param formDataListDTO
     * @param formDataListVO
     * @throws XbbException
     * @author long.rao
     * @date 2019-07-04 19:38
     */
    @Override
    public void setOption(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException{
        Map<String, FieldAttrEntity> productExplainMap = formDataListVO.getExplainMap();
        Map<Long,String> productSearchMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> dataIdList = new ArrayList<>();
        dataIdList.add(-1L);
        List<PaasFormDataEntityExt> formDataList = formDataListVO.getPaasFormDataESList();
        HashSet<Long> multiUnitIdList = new HashSet<>();
        formDataList.forEach(item -> {
            dataIdList.add(item.getId());
            if (Objects.equals(item.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), BasicConstant.ONE)) {
                multiUnitIdList.add(item.getId());
            }
        });
        String corpid = formDataListDTO.getCorpid();
        Integer subBusinessType = formDataListDTO.getSubBusinessType();
        Map<Long,JSONArray> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(subBusinessType);
        switch (redundantTemplateTypeEnum) {
            case PRODUCT:
                productMap = productListHelp.childProductList(formDataListDTO, dataIdList,corpid, productExplainMap);
                break;
            case STOCK_SEARCH:
                // 仓库权限 + 筛选
                List<Long> allWarehouseIdList = warehouseService.getWarehouseIdsByPermission(formDataListDTO.getLoginUser(),formDataListDTO.getLoginUser().getDepSet());
                List<Long> warehouseIdList = formDataListDTO.getSelectWarehouseIdList();
                if (CollectionsUtil.isEmpty(warehouseIdList)) {
                    warehouseIdList = allWarehouseIdList;
                }
                productMap = productListHelp.productWarehouseList(formDataListDTO, formDataListVO.getPaasFormDataESList(), dataIdList,corpid, warehouseIdList, productExplainMap);
                break;
            case WARNING_SEARCH:
                //productMap = productListHelp.warningInfo(dataIdList,corpid,formDataListDTO, formDataListVO, productSearchMap);
                productService.formatChildSpecification(formDataList,corpid);
                break;
            case GUARANTEE_SEARCH:
                productMap = productListHelp.batchInfo(dataIdList,corpid,formDataListDTO, formDataListVO, productSearchMap);
                productService.formatChildSpecification(formDataList,corpid);
                break;
            default:
                break;
        }

        RelativeProductExplainVO relativeProductExplainVO = saasAddHelp.getRelativeProductExplainsFromDB(corpid, subBusinessType, formDataListDTO.getListGroupId());


        Map<Long, JSONArray> multiProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //查询多单位产品价格
        if (!multiUnitIdList.isEmpty() && Objects.equals(subBusinessType, XbbRefTypeEnum.PRODUCT.getCode())) {
            ProductFieldPojo productFieldPojo = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_UNIT, ProductEnum.UNIT.getAttr(), formDataListDTO.getCorpid());
            Map<Long, List<UnitItemPoJo>> groupMap = productFieldPojo.getMultiItems().stream().collect(Collectors.toMap(MultiUnitItemPoJo::getValue, MultiUnitItemPoJo::getItemDataPoJoList));
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put(ParameterConstant.CORPID, formDataListDTO.getCorpid());
            params.put(ParameterConstant.DEL, 0);
            params.put("parentIdIn", multiUnitIdList);
            List<ProductUnitPriceEntity> entitys = productUnitPriceModel.findEntitys(params);
            for (ProductUnitPriceEntity entity : entitys) {
                Long parentId = entity.getParentId();
                JSONArray childList = multiProductMap.getOrDefault(parentId, new JSONArray());
                JSONArray price = entity.getPrice();
                List<UnitItemPoJo> unitItemPoJos = groupMap.getOrDefault(entity.getUnitGroupId(), new ArrayList<>());
                if (unitItemPoJos.size() != price.size()){
                    price = productService.formatMultiPrice(unitItemPoJos, price);
                }
                for (int i = 0; i < price.size(); i++) {
                    JSONObject child = (JSONObject) price.get(i);
                    child.put(ProductEnum.PRICE.getSaasAttr(), child.getDoubleValue(BasicConstant.RATE));
                    childList.add(child);
                }
                multiProductMap.put(parentId, childList);
            }
        }

        JSONArray tableHeadArray = saasListHelp.packageOptionTableHead(formDataListDTO.getUserId(), subBusinessType, formDataListDTO.getListGroupId(), relativeProductExplainVO);
        for (PaasFormDataEntityExt entity : formDataList){
            JSONObject data = entity.getData();
            Long dataId = entity.getId();
            JSONObject json = new JSONObject();
            JSONArray value = productMap.getOrDefault(dataId,new JSONArray());
            json.put("value", value);
            json.put("tableHead", tableHeadArray);
            if (Objects.equals(subBusinessType,XbbRefTypeEnum.PRODUCT.getCode())){
                FieldAttrEntity priceField = productExplainMap.get(ProductEnum.PRICE.getAttr());
                if (data.get(ProductEnum.PRICE.getAttr()) != null && multiUnitIdList.contains(dataId) && Objects.equals(subBusinessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                    JSONArray priceValue = multiProductMap.get(dataId);
                    if (priceValue != null) {
                        productListHelp.setParentPrice(data, priceValue, priceField);
                    }
                }else if (data.get(ProductEnum.PRICE.getAttr()) != null) {
                    productListHelp.setParentPrice(data, value, priceField);
                }
                FieldAttrEntity costField = productExplainMap.get(ProductEnum.COST.getAttr());
                if (data.get(ProductEnum.COST.getAttr()) != null) {
                    productListHelp.setParentPrice(data, value, costField);
                }
                if (Objects.equals(data.getInteger(ProductEnum.SPECIFICATION.getAttr()),1)){
                    data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
                    if (data.get(ProductEnum.SPECIFICATION.getAttr()) != null) {
                        data.put(ProductEnum.SPECIFICATION.getAttr(),value.size() + I18nMessageUtil.getMessage(I18nStringConstant.SPECIFICATION));
                    }
                } else {
                    json.put("value",new JSONArray());
                    data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
                    if (data.get(ProductEnum.SPECIFICATION.getAttr()) != null && !value.isEmpty()) {
                        data.put(ProductEnum.SPECIFICATION.getAttr(),((JSONObject)value.get(0)).getString("specification"));
                    }
                    if (data.get(ProductEnum.BARCODE.getAttr()) != null && !value.isEmpty()) {
                        data.put(ProductEnum.BARCODE.getAttr(),((JSONObject)value.get(0)).getString("barcode"));
                    }
                }
                Double totalStock = 0D;
                for (Object obj : value){
                    JSONObject jsonObject = JSONObject.parseObject(obj.toString());
                    Double stock = jsonObject.containsKey("stock") ? jsonObject.getDouble("stock") : 0D;
                    totalStock += stock;
                }
                data.put(ProductEnum.STOCK.getAttr(),totalStock);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
                //data.put(ProductEnum.SPECIFICATION.getAttr(), data.get(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                double totalStock = 0D;
                boolean isVisible = true;
                for (int i=0; i<value.size(); i++) {
                    JSONObject childObj = value.getJSONObject(i);
                    if (Objects.equals(childObj.get("stock"), BasicConstant.NULL_SHOW_STR)) {
                        isVisible = false;
                        break;
                    } else {
                        double childStock = childObj.getDoubleValue("stock");
                        totalStock = Arith.add(totalStock, childStock);
                    }
                }
                if (isVisible) {
                    data.put(ProductEnum.STOCK.getAttr(), totalStock);
                } else {
                    data.put(ProductEnum.STOCK.getAttr(), BasicConstant.NULL_SHOW_STR);
                }

                data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
            } else {
                data.put(ListOptionEnum.MULTI_SPEC.getAttr(), json);
            }
            if (Objects.equals(subBusinessType,XbbRefTypeEnum.WARNING_SEARCH.getCode())){
                data.put(ListOptionEnum.WARNING_SEARCH.getAttr(), productSearchMap.get(dataId));
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())){
//                data.put(ListOptionEnum.GUARANTEE_SEARCH.getAttr(), productSearchMap.get(dataId));
            }

        }
    }

    @Override
    public PaasFormDataEsListVO subFormList(SubFormListDTO subFormListDTO) throws XbbException {
        Long dataId = subFormListDTO.getDataId();
        String corpid = subFormListDTO.getCorpid();
        Integer businessType = subFormListDTO.getBusinessType();
        PaasFormDataEntityExt paasFormDataEntityExt;
        if (Objects.equals(businessType, XbbRefTypeEnum.WARNING_SEARCH.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
            subFormListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        }

        if (Objects.equals(SaasMarkEnum.SAAS.getCode(),subFormListDTO.getSaasMark())){
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(),businessType)) {
                paasFormDataEntityExt = workOrderModel.getByKey(dataId, corpid);
            }else {
                paasFormDataEntityExt = baseHelp.getFormData(dataId,corpid,businessType);
            }
            if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) && !Objects.equals(0L, paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
                // 拿下父产品的数据
                paasFormDataEntityExt = baseHelp.getFormData(paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()), corpid, businessType);
            }
        }else {
            paasFormDataEntityExt = paasFormDataModel.getByKey(dataId,corpid);
        }
        Long formId = paasFormDataEntityExt.getFormId();
        //正常列表是从es获取的，从数据库获取没有这个值
        paasFormDataEntityExt.setDataId(paasFormDataEntityExt.getId());
        PaasFormExplainEntity paasFormExplainEntity;
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(),businessType)){
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formId,corpid);
            paasFormExplainEntity = new PaasFormExplainEntity();
            BeanUtil.copyProperties(workOrderExplainEntity,paasFormExplainEntity);
        }else if (Objects.equals(businessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.WRITE_OFF_RECORD.getCode())){
            paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
            formId = subFormListDTO.getFormId();
        }else {
            paasFormExplainEntity  = paasFormExplainModel.getByFormId(formId,corpid);
        }
        // 经销商业务改businessType
        Integer distributorMark = paasFormExplainEntity.getDistributorMark();
        if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
            subFormListDTO.setBusinessType(XbbRefTypeEnum.transferBusinessType4Distributor(businessType, distributorMark));
        }
        List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        boolean catchFieldAttr = false;
        List<FieldAttrEntity> subFormAttrList = new ArrayList<>();
        String attr = subFormListDTO.getAttr();
        boolean isProduct = false;
        Map<String,FieldAttrEntity> expalinMap = new HashMap<>();
        for (FieldAttrEntity entity : fieldAttrEntityList){
            expalinMap.put(entity.getAttr(),entity);
            if (Objects.equals(attr,entity.getAttr())){
                if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(),entity.getFieldType()) || Objects.equals(FieldTypeEnum.CONTACT_NUMBER.getType(),entity.getFieldType())){
                    catchFieldAttr = true;
                    for (FieldAttrEntity subAttrEntity : entity.getSubForm().getItems()){
                        // 字段回收站处理
                        if (Objects.equals(subAttrEntity.getIsOpen(), 2)) {
                            subAttrEntity.setVisible(0);
                        }
                        subFormAttrList.add(subAttrEntity);
//                        explainMap.put(subAttrEntity.getAttr(),subAttrEntity);
                    }
                    break;
                }else if (Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType(),entity.getFieldType())) {
                    Boolean isJxcUse = true;
                    if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.WORK_ORDER.getCode())) {
                        isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                    }
                    proFormHelp.setProductAccuracy(entity,corpid,subFormListDTO.getUserId());
                    for (Object obj : entity.getSubForm().getItems()){
                        FieldAttrEntity subAttrEntity = JSONObject.parseObject(JSONObject.toJSONString(obj),FieldAttrEntity.class);
                        if (!ShowTypeEnum.listShow(subAttrEntity.getShowType())){
                            continue;
                        }

                        // 字段回收站处理
                        if (Objects.equals(subAttrEntity.getIsOpen(), 2)) {
                            subAttrEntity.setVisible(0);
                        }
                        if (Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.PRODUCT.getAttr())){
                            subAttrEntity.setFieldType(FieldTypeEnum.TEXT.getType());
                        }else if (Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.UNIT.getAttr())){
                            Long productFormId = paasFormModel.getFormIdByBusinessType(corpid,XbbRefTypeEnum.PRODUCT.getCode());
                            List<ItemPoJo> itemPojoList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.PRODUCT_UNIT,corpid,productFormId);
                            subAttrEntity.setItems(itemPojoList);
                        }else if (!isJxcUse && Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())){
                            if (Objects.equals(subAttrEntity.getAttr(), SelectProductEnum.SOURCE_DOC.getAttr())
                                    || Objects.equals(subAttrEntity.getAttr(), RefundProductEnum.INSTOCK_NUM.getAttr())
                                    || Objects.equals(subAttrEntity.getAttr(), RefundProductEnum.WAIT_INSTOCK_NUM.getAttr())
                                    || Objects.equals(subAttrEntity.getAttr(), RefundProductEnum.BATCH.getAttr())
                                    || Objects.equals(subAttrEntity.getAttr(), RefundProductEnum.GUARANTEE_PERIOD.getAttr())
                                    || Objects.equals(subAttrEntity.getAttr(), RefundProductEnum.PRODUCE_DATE.getAttr())
                                    || Objects.equals(subAttrEntity.getAttr(), RefundProductEnum.EXPIRE_DATE.getAttr())) {
                                continue;
                            }
                        }else if (!isJxcUse && Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())){
                            if ((Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.OUTSTOCK_NUM.getAttr())
                                    || Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr())
                                    || Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.RETURN_NUM.getAttr()))) {
                                continue;
                            }
                        }else if (!isJxcUse && Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())){
                            if ((Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.OUTSTOCK_NUM.getAttr()) || Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr()))) {
                                continue;
                            }
                        }else if (Objects.equals(businessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
                            if ((Objects.equals(subAttrEntity.getAttr(),SelectProductEnum.SPECIFICATION.getAttr()))) {
                                continue;
                            }
                        }
                        subFormAttrList.add(subAttrEntity);
//                        explainMap.put(subAttrEntity.getAttr(),subAttrEntity);
                    }
                    isProduct = true;
                    catchFieldAttr = true;
                    break;
                }else {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.NOT_SUBFORM_FIELDS);
                }
            }
        }
        if (!catchFieldAttr){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.NOT_EXIST_FIELD);
        }

        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        PageHelper pageHelper = new PageHelper();
        FieldAttrEntity subFormField = expalinMap.get(subFormListDTO.getAttr());
        if (Objects.nonNull(subFormField)) {
            //协同团队
            List<String> ownerIdList;
            List<String> coUserList;
            List<Long> dataIdList = new ArrayList<>();
            dataIdList.add(dataId);
            if (UserTeamEnum.hasTeam(businessType)){
                Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), businessType);
                userTeamService.getUserIdMap(dataIdList,corpid,businessType,isPublic,mainUserMap,coUserMap);
                ownerIdList = mainUserMap.get(dataId);
                coUserList = coUserMap.get(dataId);
            } else {
                // 协同人
                CoUserListDTO coUserListDTO = new CoUserListDTO(paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getFormId(), dataIdList, corpid);
                Map<Long, List<String>> paasCoUserMap = coUserService.coUserMap(coUserListDTO);
                ownerIdList = Collections.singletonList(paasFormDataEntityExt.getOwnerId());
                coUserList = paasCoUserMap.get(dataId);
            }
            String creatorId = paasFormDataEntityExt.getCreatorId();
            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                creatorId = paasFormDataEntityExt.getData().getString(CustomerManagementEnum.CREATOR.getAttr());
            }
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(creatorId, ownerIdList, coUserList, subFormListDTO.getUserId(), subFormListDTO.getLoginUser());
            if (ExplainUtil.invisibleOfScope(subFormField, handlerExplainDTO)) {
                formDataListVO.setPageHelper(pageHelper);
                formDataListVO.setPaasFormDataESList(new ArrayList<>());
                formDataListVO.setHeadList(subFormAttrList);
                return formDataListVO;
            }
        }
        JSONObject data = paasFormDataEntityExt.getData();
        //模拟分页校验
        Integer page = subFormListDTO.getPage();
        Integer pageSize = subFormListDTO.getPageSize();
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 5 : pageSize;
        page = page < 1 ? 1 : page;
        Integer start = (page - 1) * pageSize;
        List<PaasFormDataEntityExt> list = new ArrayList<>();
        Integer total = 0;
        if (isProduct){
            //排序功能
            RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
            PagingProductDTO pagingProductDTO = new PagingProductDTO();
            BeanUtils.copyProperties(subFormListDTO,pagingProductDTO);
            pagingProductDTO.setData(new JSONObject());
            pagingProductDTO.setUpdateDataTypeEnum(UpdateDataTypeEnum.DETAIL);
            PagingProductVO pagingProductVO = new PagingProductVO();
            switch (redundantTemplateTypeEnum){
                case CONTRACT:
                    pagingProductVO = contractService.getPagingProduct(pagingProductDTO);
                    if ( Objects.isNull(pagingProductVO) ) {
                        JSONArray productDataArr = pagingProductVO.getProductDataArr();
                        paasFormDataEntityExt.getData().put(ContractEnum.PRODUCT.getAttr(), productDataArr);
                    }
                    break;
                default:
                    break;
            }
            List<PaasFormDataEntityExt> listProduct = new ArrayList<>();
            listProduct.add(paasFormDataEntityExt);
            FormDataListDTO formDataListDTO = new FormDataListDTO();
            BeanUtil.copyProperties(subFormListDTO, formDataListDTO);
            formDataListDTO.setExplainMap(expalinMap);
            // 这里用的是中间状态的businessType 后面如果要区分好写
            Map<String,List<FieldAttrEntity>> keyListMap = saasListHelp.analysisListProductData(listProduct,Collections.singletonList(subFormListDTO.getDataId()),subFormListDTO.getBusinessType(),corpid,start,pageSize, formDataListDTO);
            int type = 0;
            Long refDataId = subFormListDTO.getDataId();
            if (Objects.equals(businessType,XbbRefTypeEnum.ASSEMBLE.getCode())){
                if (Objects.equals(attr,AssembleEnum.OUT_PRODUCTS.getAttr())){
                    type = 1;
                }else {
                    type = 2;
                }
            }else if (Objects.equals(businessType,XbbRefTypeEnum.BOM_BILL.getCode())){
                if (Objects.equals(attr,BomBillEnum.PRODUCT.getAttr())){
                    type = 1;
                }else {
                    type = 2;
                }
            }else if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCTION_ORDER.getCode())){
                if (Objects.equals(attr,ProductionOrderEnum.PRODUCT.getAttr())){
                    type = 1;
                }else {
                    type = 2;
                }
            }else if (Objects.equals(businessType,XbbRefTypeEnum.REFUND.getCode())){
                refDataId = paasFormDataEntityExt.getData().getLong(RefundEnum.RED_CONTRACT_ID.getAttr());
            }
            // 这里用的是中间状态的businessType 后面如果要区分好写
            total = saasListHelp.getRefProductListTotal(refDataId,subFormListDTO.getBusinessType(),corpid,type);
            List<Object> productData = paasFormDataEntityExt.getData().getJSONArray(attr);
            for (Object obj : productData){
                PaasFormDataEntityExt entityExt = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(paasFormDataEntityExt,entityExt);
                entityExt.setData(JSONObject.parseObject(obj.toString()));
                list.add(entityExt);
            }
            if (keyListMap.containsKey(subFormListDTO.getAttr())) {
                int index = 0;
                int productIndex = -1;
                for (FieldAttrEntity entity : subFormAttrList) {
                    if (Objects.equals(entity.getAttr(), SelectProductEnum.PRODUCT.getAttr())) {
                        productIndex = index;
                        break;
                    }
                    index++;
                }
                if (productIndex >= 0) {
                    subFormAttrList.addAll(productIndex+1, keyListMap.get(subFormListDTO.getAttr()));
                }
            }
            formDataListVO.setPaasFormDataESList(list);
            formDataListVO.setHeadList(subFormAttrList);
        }else {
            List<JSONObject> attrDataList = JSONArray.parseArray(data.getString(attr),JSONObject.class);
            // 22401 【成功部】客户单个联系人有多个联系方式，设置为主联系人后，客户列表页查看对应全部联系方式提示网络请求失败，无法完整查看。
            if(Objects.equals(subFormListDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())
                    && Objects.equals(attr, CustomerManagementEnum.CONTACT_PHONE.getAttr()) && Objects.equals(0, subFormField.getIsRedundant())){
                // 查询客户的主联系人
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termQuery("data." + ContactEnum.IS_MAIN.getAttr(), 1));
                boolQueryBuilder.filter(termsQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.CUSTOMER_NAME),Arrays.asList(paasFormDataEntityExt.getDataId())));
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
                sourceBuilder.query(boolQueryBuilder);
                SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTACT.getIndex());
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, 1);
                searchRequest.source(sourceBuilder);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
                if(esEntities == null){
                    return formDataListVO;
                }
                if(esEntities.getContent().size() < 1){
                    return formDataListVO;
                }
                PaasFormDataEntityExt contactExt = esEntities.getContent().get(0);

                Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

                PaasFormExplainEntity contactExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTACT.getCode(), corpid);
                if (Objects.isNull(contactExplain)) {
                    throw new XbbException(ApprovalErrorCodeEnum.API_ERROR_209012);
                }
                Map<String, FieldAttrEntity> explainMapByAttr = ExplainUtil.getExplainMapByAttr(contactExplain.getExplains(), ContactEnum.PHONE.getAttr());
                FieldAttrEntity fieldAttrEntity = explainMapByAttr.get(ContactEnum.PHONE.getAttr());
                if (Objects.isNull(fieldAttrEntity)) {
                    return formDataListVO;
                }
                userTeamService.getUserIdMap(Collections.singletonList(contactExt.getId()), corpid, XbbRefTypeEnum.CONTACT.getCode(), false, mainUserMap, coUserMap);
                HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                BeanUtil.copyProperties(subFormListDTO, handlerExplainDTO);
                handlerExplainDTO.setCreatorId(contactExt.getCreatorId());
                handlerExplainDTO.setOwnerId(mainUserMap.getOrDefault(contactExt.getId(), new ArrayList<>()));
                handlerExplainDTO.setCoUserId(coUserMap.getOrDefault(contactExt.getId(), new ArrayList<>()));
                Boolean fieldNeedHide = ExplainUtil.isFieldNeedHide(fieldAttrEntity, handlerExplainDTO);
                if (fieldNeedHide) {
                    return formDataListVO;
                }
                Boolean contactPhoneHide = false;
                Map<String, FieldAttrEntity> phoneExplainMap = new HashMap<>(fieldAttrEntity.getSubForm().getItems().size());
                for (FieldAttrEntity subAttrEntity : fieldAttrEntity.getSubForm().getItems()){
                    if (Objects.equals(subAttrEntity.getAttr(), StringConstant.PHONE_TEL_ATTR)) {
                        contactPhoneHide = ExplainUtil.isFieldNeedHide(subAttrEntity, handlerExplainDTO);
                    }
                    phoneExplainMap.put(subAttrEntity.getAttr(), subAttrEntity);
                }
                if (contactPhoneHide) {
                    return formDataListVO;
                }
                JSONArray contactPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(contactExt.getData(), ContactEnum.PHONE.getAttr(), new JSONArray());
                attrDataList = JSONArray.parseArray(JSON.toJSONString(contactPhoneArray), JSONObject.class);
                subFormAttrList.forEach(item->{
                    if (phoneExplainMap.containsKey(item.getAttr())) {
                        // 客户“主联系人电话”“类型”同步联系人的“联系电话”中“类型”选项
                        item.setItems(phoneExplainMap.get(item.getAttr()).getItems());
                    }
                });
            } else if (Objects.equals(subFormListDTO.getBusinessType(), XbbRefTypeEnum.COMMUNICATE_PLAN.getCode())
                    && Objects.equals(attr, CommunicatePlanEnum.CONTACT_WAY.getAttr()) && Objects.equals(0, subFormField.getIsRedundant())) {
                HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                handlerExplainDTO.setLoginUser(subFormListDTO.getLoginUser());
                handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
                proDetailHandlerHelp.handleDetailSpecialField(data, dataId, businessType, corpid, expalinMap, formId, handlerExplainDTO);
                attrDataList = JSONArray.parseArray(data.getString(CommunicatePlanEnum.CONTACT_WAY.getAttr()),JSONObject.class);
            }
            if (Objects.nonNull(attrDataList) && Objects.equals(subFormListDTO.getBusinessType(), XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode()) && Objects.equals(attr, DistributorEnum.SHIPPING_ADDRESS.getAttr())) {
                for (JSONObject obj : attrDataList) {
                    // 处理收货地址默认值回显
                    String defaultAttr = DistributorAddressEnum.SET_DEFAULT.getAttr();
                    if (obj != null && obj.containsKey(defaultAttr)) {
                        int defaultVal = (int) obj.get(defaultAttr);
                        obj.put(defaultAttr, defaultVal == BasicConstant.IS_DEFAULT ? "是" : "否");
                    }
                }
            }
            attrDataList = Objects.isNull(attrDataList) ? new ArrayList<>() : attrDataList;
            Integer dataSize = attrDataList.size();
            Integer end = start + pageSize;
            end = end > dataSize ? dataSize : end;
            if (dataSize < start + 1){
//            formDataListVO.setPaasFormDataESList(new ArrayList<>());
            }else {
                List<JSONObject> subAttrDataList = attrDataList.subList(start,end);
                for (JSONObject json : subAttrDataList){
                    PaasFormDataEntityExt entityExt = new PaasFormDataEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntityExt,entityExt);
                    entityExt.setData(json);
                    list.add(entityExt);
                }
            }
            formDataListVO.setHeadList(subFormAttrList);
            formDataListVO.setPaasFormDataESList(list);
            total = attrDataList.size();
        }
        List<FieldAttrEntity> headList = formDataListVO.getHeadList();
        if (CollectionsUtil.isNotEmpty(headList)) {
            Iterator<FieldAttrEntity> iterator = headList.iterator();
            while (iterator.hasNext()) {
                if (Objects.equals(iterator.next().getVisible(), 0)) {
                    iterator.remove();
                }
            }
            formDataListVO.setHeadList(headList);
        }
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(subFormListDTO,formDataListDTO);
        formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
        //子表单金额千分位解析
        formDataListAnalysisDataHelp.analysisAmountOfThousandBits(formDataListVO, formDataListDTO.getAnalysisAmountOfThousandBitsWithOriginalValue());
        pageHelper = new PageHelper(page,pageSize);
        pageHelper.setRowsCount(total);
        formDataListVO.setPageHelper(pageHelper);
        return formDataListVO;
    }

    @Override
    public PaasFormDataEsListVO stockFlowBillList(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions();
        if (CollectionsUtil.isNotEmpty(formDataListDTO.getProductSearchIds())) {
            conditionList.add(new ConditionsEntityExt(StockFlowBillEnum.NAME.getAttr(), null, null, null, new ArrayList<>(formDataListDTO.getProductSearchIds())));
        }
        String corpid = formDataListDTO.getCorpid();
        Long formId = formDataListDTO.getFormId();
        Integer page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();
        // 查询表单，解释
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        paasFormDataEsListVO.setForm(paasFormEntityExt);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        // 解释处理
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        explainList.forEach(item -> {
            item.setDisableListSort(1);
            item.setEditable(0);
            if (Objects.equals(item.getAttr(), StockFlowBillEnum.TIME.getAttr())) {
                item.setDateType(DateTimeEnum.TIME.getType());
            }
        });
        paasFormDataEsListVO.setHeadList(explainList);
        paasFormDataEsListVO.setBusinessType(formDataListDTO.getBusinessType());
        formDataListSearchHelp.setButtons(formDataListDTO, paasFormDataEsListVO);
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        //表单冻结和隐藏列设置（在按钮设置后处理，防止操作列无法冻结和隐藏）
        formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, paasFormDataEsListVO);
        // 查看权限，没有则返回空列表
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!permSet.contains(ProPermissionAliasEnum.STOCK_FLOW_BILL_VIEW.getAlias())) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        // 仓库权限
        List<Long> warehouseIdList = warehouseService.getWarehouseIdsByPermission(formDataListDTO.getLoginUser(), formDataListDTO.getLoginUser().getDepSet());
        // 查询条件
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("start", (page - 1) * pageSize);
        params.put("pageNum", pageSize);
        params.put("warehouseIdIn", warehouseIdList);
        // 需要取交集的动作，难顶
        List<Integer> businessTypeList = new ArrayList<>();
        boolean hasBusinessType = false;
        // 产品筛选和仓库筛选
        for (ConditionsEntityExt conditionsEntityExt : conditionList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), StockFlowBillEnum.NAME.getAttr())) {
                params.put("productIdIn", conditionsEntityExt.getValue());
            } else if (Objects.equals(conditionsEntityExt.getAttr(), StockFlowBillEnum.WAREHOUSE_ID.getAttr())) {
                params.put("warehouseIdIn", conditionsEntityExt.getValue());
            } else if (Objects.equals(conditionsEntityExt.getAttr(), StockFlowBillEnum.TYPE.getAttr())) {
                params.put("businessType", conditionsEntityExt.getValue().get(0));
            } else if (Objects.equals(conditionsEntityExt.getAttr(), StockFlowBillEnum.BUSINESS_ID.getAttr()) && Objects.nonNull(conditionsEntityExt.getValue()) && !conditionsEntityExt.getValue().isEmpty()) {
                StockFilterTypeEnum stockFilterTypeEnum = StockFilterTypeEnum.getByAttr(conditionsEntityExt.getSubAttr());
                if (Objects.nonNull(stockFilterTypeEnum)) {
                    params.put("businessId", conditionsEntityExt.getValue().get(0));
                    hasBusinessType = true;
                    if (businessTypeList.isEmpty()) {
                        businessTypeList.addAll(stockFilterTypeEnum.getBusinessTypeList());
                    } else {
                        businessTypeList.retainAll(stockFilterTypeEnum.getBusinessTypeList());
                    }
                }
            }
        }
        // 常用筛选 单据编号和往来单位
        JSONObject commonFilter = formDataListDTO.getCommonFilter();
        if (Objects.nonNull(commonFilter) && !commonFilter.isEmpty()) {
            if (Objects.nonNull(commonFilter.getJSONObject(FieldTypeEnum.REF_ID.getAlias())) && StringUtil.isNotEmpty(commonFilter.getJSONObject(FieldTypeEnum.REF_ID.getAlias()).getString("value"))) {
                StockFilterTypeEnum stockFilterTypeEnum = StockFilterTypeEnum.getByAttr(commonFilter.getJSONObject(FieldTypeEnum.REF_ID.getAlias()).getString("attr"));
                if (Objects.nonNull(stockFilterTypeEnum)) {
                    params.put("refId", commonFilter.getJSONObject(FieldTypeEnum.REF_ID.getAlias()).getLong("value"));
                    hasBusinessType = true;
                    if (businessTypeList.isEmpty()) {
                        businessTypeList.addAll(stockFilterTypeEnum.getBusinessTypeList());
                    } else {
                        businessTypeList.retainAll(stockFilterTypeEnum.getBusinessTypeList());
                    }
                }
            } else if (Objects.nonNull(commonFilter.getJSONObject(FieldTypeEnum.BUSINESS_ID.getAlias())) && StringUtil.isNotEmpty(commonFilter.getJSONObject(FieldTypeEnum.BUSINESS_ID.getAlias()).getString("value"))) {
                StockFilterTypeEnum stockFilterTypeEnum = StockFilterTypeEnum.getByAttr(commonFilter.getJSONObject(FieldTypeEnum.BUSINESS_ID.getAlias()).getString("attr"));
                if (Objects.nonNull(stockFilterTypeEnum)) {
                    params.put("businessId", commonFilter.getJSONObject(FieldTypeEnum.BUSINESS_ID.getAlias()).getLong("value"));
                    hasBusinessType = true;
                    if (businessTypeList.isEmpty()) {
                        businessTypeList.addAll(stockFilterTypeEnum.getBusinessTypeList());
                    } else {
                        businessTypeList.retainAll(stockFilterTypeEnum.getBusinessTypeList());
                    }
                }
            }
        }
        if (hasBusinessType) {
            businessTypeList.add(-1);
            params.put("businessTypeIn", businessTypeList);
        }
        // 日期筛选
        FiscalYearTimePojo fiscalYearTimePojo = formDataListDTO.getTimeFilter() == null ? new FiscalYearTimePojo() : formDataListDTO.getTimeFilter();
        // 财年开始月份，这里应该没有财年这个概念吧
        // int startMonth = companyConfigModel.getFiscalStartMonth(formDataListDTO.getCorpid());
        int startMonth = 1;
        fiscalYearTimePojo.setStartMonth(startMonth);
        Integer timeType = fiscalYearTimePojo.getTimeType4DefaultDay();
        TimeTypeEnum timeTypeEnum = TimeTypeEnum.getByCode(timeType);
        if (timeTypeEnum == null) {
            timeType = TimeTypeEnum.DAY.getCode();
        }
        fiscalYearTimePojo.setTimeTypeEnum(timeTypeEnum);
        Integer startTime = FiscalYearHelp.getStartTime(fiscalYearTimePojo, timeType, startMonth);
        Integer endTime = FiscalYearHelp.getEndTime(fiscalYearTimePojo, startTime, timeType, startMonth);
        params.put("greaterEqualThanDate", startTime);
        params.put("lessThanDate", endTime);
        String orderByStr = " date asc, id asc";
        if (Objects.nonNull(formDataListDTO.getSortMap())) {
            if(SortOrder.DESC.toString().equals(formDataListDTO.getSortMap().get("sort"))){
                orderByStr = " date desc, id desc";
            }
        }
        params.put("orderByStr", orderByStr);
        // 流水分页信息
        List<StockFlowBillEntity> stockFlowBillList = stockFlowBillModel.findEntitys(params);
        if (stockFlowBillList.size() == 0) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        Integer count = stockFlowBillModel.getEntitysCount(params);
        paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(count));
        // 产品信息和仓库信息
        Set<Long> productIdSet = new HashSet<>();
        Set<Long> warehouseIdSet = new HashSet<>();
        stockFlowBillList.forEach(item -> {
            productIdSet.add(item.getProductId());
            warehouseIdSet.add(item.getWarehouseId());
        });
        List<PaasFormDataEntityExt> productEntityList = productService.getProductListById(productIdSet, corpid, DelEnum.NORMAL);
        params.clear();
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("idIn", warehouseIdSet);
        List<WarehouseEntityExt> warehouseEntityList = warehouseModel.findEntitys(params);
        Map<Long, WarehouseEntityExt> warehouseMap = new HashMap<>(warehouseEntityList.size());
        warehouseEntityList.forEach(item -> warehouseMap.put(item.getId(), item));
        productService.formatChildSpecification(productEntityList, corpid);
        Map<Long, String> categoryMap = productListHelp.categoryList(formDataListDTO.getCorpid());
        productEntityList.forEach(item -> {
            Long categoryId = item.getData().getLong(ProductEnum.CATEGORY_ID.getAttr());
            item.getData().put(ProductEnum.CATEGORY_ID.getAttr(), categoryMap.getOrDefault(categoryId, ""));
        });
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(productEntityList.size());
        productEntityList.forEach(item -> productMap.put(item.getDataId(), item));
        // 列表数据封装
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>(stockFlowBillList.size());
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setLoginUser(formDataListDTO.getLoginUser());
        handlerExplainDTO.setUserId(formDataListDTO.getLoginUser().getUserId());
        PaasFormExplainEntity productExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        Map<String, FieldAttrEntity> productExplainMap = ExplainUtil.getExplainMap(productExplainEntity.getExplains(), null);
        // 产品成本权限
        FieldAttrEntity costFieldPojo = productExplainMap.get(ProductEnum.COST.getAttr());
        boolean costVisible = Objects.equals(costFieldPojo.getVisible(), 1) && !ExplainUtil.invisibleOfScope(costFieldPojo, handlerExplainDTO);
        boolean isAmount = Objects.equals(costFieldPojo.getAmountFlag(), 1);
        Integer costAccuracy = costFieldPojo.getAccuracy();
        // 库存数量精度
        FieldAttrEntity stockField = productExplainMap.get(ProductEnum.STOCK.getAttr());
        Integer stockAccuracy = stockField.getAccuracy();
        // 单位解释
        FieldAttrEntity unitFieldPojo = productExplainMap.get(ProductEnum.UNIT.getAttr());
        // 高级权限样式
        String invisibleStyle = StringConstant.INVISIBLE_VALUE;
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (!notExport) {
            invisibleStyle = null;
        }
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        for (StockFlowBillEntity stockFlowBillEntity : stockFlowBillList) {
            Long productId = stockFlowBillEntity.getProductId();
            Long warehouseId = stockFlowBillEntity.getWarehouseId();
            Integer stockType = stockFlowBillEntity.getStockType();
            String refSheetNo = stockFlowBillEntity.getRefSheetNo();
            Long date = stockFlowBillEntity.getDate();
            Integer businessType = stockFlowBillEntity.getBusinessType();
            Double productNum = attrDecimalPrecisionHelper.setPrecision(stockFlowBillEntity.getNum(), stockAccuracy);
            Double remainingStock = attrDecimalPrecisionHelper.setPrecision(stockFlowBillEntity.getRemainingStock(), stockAccuracy);
            Object productCost;
            Object remainingCost;
            if (isAmount) {
                productCost = AttrDecimalPrecisionHelper.parseThousandth(stockFlowBillEntity.getProductCost(), costAccuracy);
                remainingCost = AttrDecimalPrecisionHelper.parseThousandth(stockFlowBillEntity.getRemainingCost(), costAccuracy);
            } else {
                productCost = attrDecimalPrecisionHelper.setPrecision(stockFlowBillEntity.getProductCost(), costAccuracy);
                remainingCost = attrDecimalPrecisionHelper.setPrecision(stockFlowBillEntity.getRemainingCost(), costAccuracy);
            }
            boolean isOutStock = Objects.equals(stockType, 2);
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setDataId(stockFlowBillEntity.getId());
            JSONObject data = new JSONObject();
            // 产品信息封装
            if (productMap.containsKey(productId)) {
                PaasFormDataEntityExt product = productMap.get(productId);
                JSONObject productObj = product.getData();
                data.put(StockFlowBillEnum.SERIALNO.getAttr(), product.getSerialNo());
                data.put(StockFlowBillEnum.NAME.getAttr(), productObj.getString(ProductEnum.NAME.getAttr()));
                data.put(StockFlowBillEnum.SPECIFICATION.getAttr(), productObj.getString(ProductEnum.SPECIFICATION.getAttr()));
                data.put(StockFlowBillEnum.CATEGORY_ID.getAttr(), productObj.getString(ProductEnum.CATEGORY_ID.getAttr()));
                String unitStr = FastJsonHelper.getStringOrDefaultFromFormData(productObj, ProductEnum.UNIT.getAttr(), "");
                String unit = "";
                // 多单位
                if (BasicConstant.ONE.equals(productObj.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr())) && StringUtil.isNotEmpty(unitStr)) {
                    data.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), data.getLongValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                    MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(Long.parseLong(unitStr));
                    unit = multiUnitItemPoJo.getBaseName();
                } else {
                    unit = fieldAttrHelp.getDataDictionaryTextByValue(unitStr, unitFieldPojo);
                }
                data.put(StockFlowBillEnum.UNIT.getAttr(), unit);
                if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                    data.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), productObj.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()));
                }
            }
            // 仓库信息封装
            if (warehouseMap.containsKey(warehouseId)) {
                WarehouseEntityExt warehouse = warehouseMap.get(warehouseId);
                JSONObject warehouseObj = warehouse.getData();
                data.put(StockFlowBillEnum.WAREHOUSE_ID.getAttr(), warehouseObj.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
            }
            // 其他基础信息封装
            if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue()) || !notExport) {
                data.put(StockFlowBillEnum.SHEET_NO.getAttr(), refSheetNo);
                data.put(StockFlowBillEnum.TIME.getAttr(), DateTimeUtil.getStringEpochSecond(date, DateTimeUtil.SDFDate));
            } else {
                JSONArray sheetArray = new JSONArray();
                JSONObject sheetObject = new JSONObject();
                sheetObject.put("name", refSheetNo);
                // 期初穿透仓库详情页
                if (Objects.equals(businessType, XbbRefTypeEnum.ORI_STOCK.getCode())) {
                    sheetObject.put("id", warehouseId);
                    sheetObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
                    sheetObject.put("businessType", XbbRefTypeEnum.WAREHOUSE.getCode());
                } else {
                    sheetObject.put("id", stockFlowBillEntity.getRefId());
                    sheetObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
                    sheetObject.put("businessType", businessType);
                }
                sheetArray.add(sheetObject);
                data.put(StockFlowBillEnum.SHEET_NO.getAttr(), sheetArray);
                data.put(StockFlowBillEnum.TIME.getAttr(), date);
            }

            if (notExport) {
                data.put(StockFlowBillEnum.TYPE.getAttr(), new ItemPoJo(XbbRefTypeEnum.getByCode(businessType).getName(), null, false, null));
            } else {
                // 导出
                data.put(StockFlowBillEnum.TYPE.getAttr(), XbbRefTypeEnum.getByCode(businessType).getName());
            }
            data.put(StockFlowBillEnum.BUSINESS_ID.getAttr(), stockFlowBillEntity.getBusinessName());
            data.put(StockFlowBillEnum.MEMO.getAttr(), stockFlowBillEntity.getMemo());
            // 出入库数据封装
            JSONArray outInArray = new JSONArray();
            JSONObject outInObject = new JSONObject();
            if (isOutStock) {
                outInObject.put("num_1",  "-" + AttrDecimalPrecisionHelper.setPrecisionStr(productNum.toString(), stockAccuracy));
            } else {
                outInObject.put("num_1", "+" + AttrDecimalPrecisionHelper.setPrecisionStr(productNum.toString(), stockAccuracy));
            }
            if (costVisible) {
                outInObject.put("num_2", productCost);
                if (isAmount) {
                    outInObject.put("num_3", AttrDecimalPrecisionHelper.parseThousandth(Arith.mul(productNum, Arith.round(stockFlowBillEntity.getProductCost(), costAccuracy)), costAccuracy));
                } else {
                    outInObject.put("num_3", attrDecimalPrecisionHelper.setPrecision(Arith.mul(productNum, Arith.round(stockFlowBillEntity.getProductCost(),costAccuracy)), costAccuracy));
                }
            } else {
                outInObject.put("num_2", invisibleStyle);
                outInObject.put("num_3", invisibleStyle);
            }
            outInArray.add(outInObject);
            data.put(StockFlowBillEnum.OUT_IN_RECORD.getAttr(), outInArray);
            // 结存数据封装
            JSONArray remainArray = new JSONArray();
            JSONObject remainObject = new JSONObject();
            remainObject.put("num_1", remainingStock);
            if (costVisible) {
                remainObject.put("num_3", remainingCost);
                if (!Objects.equals(remainingStock, 0D)) {
                    if (isAmount) {
                        remainObject.put("num_2", attrDecimalPrecisionHelper.parseThousandth(Arith.div(Arith.round(stockFlowBillEntity.getRemainingCost(), costAccuracy), remainingStock), costAccuracy));
                    } else {
                        remainObject.put("num_2", attrDecimalPrecisionHelper.setPrecision(Arith.div(Arith.round(stockFlowBillEntity.getRemainingCost(), costAccuracy), remainingStock), costAccuracy));
                    }
                } else {
                    // 移动端需要占位, 给个空字符串。
                    if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                        remainObject.put("num_2", "");
                    }
                }
            } else {
                remainObject.put("num_2", invisibleStyle);
                remainObject.put("num_3", invisibleStyle);
            }
            remainArray.add(remainObject);
            data.put(StockFlowBillEnum.REMAINING_STOCK.getAttr(), remainArray);
            paasFormDataEntityExt.setData(data);
            paasFormDataESList.add(paasFormDataEntityExt);
        }
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO distributorAccountList(FormDataListDTO formDataListDTO) throws XbbException {
            formDataListDTO.setBusinessType(XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode());
            formDataListDTO.setSubBusinessType(XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode());
            AbstractWebDataAnalysisHandle abstractWebDataAnalysisHandle = webDataAnalysisFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
            if (Objects.isNull(abstractWebDataAnalysisHandle)) {
                return null;
            }
            PaasFormDataEsListVO paasFormDataEsListVO = abstractWebDataAnalysisHandle.analysisData(formDataListDTO);
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
            if (notExport){
                paasFormDataEsListVO.setExplainMap(new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
            }
            return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO stockStandingBookList(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions();
        if (CollectionsUtil.isNotEmpty(formDataListDTO.getProductSearchIds())) {
            conditionList.add(new ConditionsEntityExt(StockFlowBillEnum.NAME.getAttr(), null, null, null, new ArrayList<>(formDataListDTO.getProductSearchIds())));
        }
        String corpid = formDataListDTO.getCorpid();
        Long formId = formDataListDTO.getFormId();
        Integer page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();
        // 查询表单，解释
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        paasFormDataEsListVO.setForm(paasFormEntityExt);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        explainList.forEach(item -> {
            item.setDisableListSort(1);
            item.setEditable(0);
        });
        paasFormDataEsListVO.setHeadList(explainList);
        paasFormDataEsListVO.setBusinessType(formDataListDTO.getBusinessType());
        formDataListSearchHelp.setButtons(formDataListDTO, paasFormDataEsListVO);
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        //表单冻结和隐藏列设置（在按钮设置后处理，防止操作列无法冻结和隐藏）
        formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, paasFormDataEsListVO);
        // 查看权限，没有则返回空列表
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!permSet.contains(ProPermissionAliasEnum.STOCK_STANDING_BOOK_VIEW.getAlias())) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        // 仓库权限
        List<Long> warehouseIdList = warehouseService.getWarehouseIdsByPermission(formDataListDTO.getLoginUser(), formDataListDTO.getLoginUser().getDepSet());
        // 查询条件
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("start", (page - 1) * pageSize);
        params.put("pageNum", pageSize);
        params.put("warehouseIdIn", warehouseIdList);
        params.put("groupByStr", "warehouse_key");
        // 产品筛选和仓库筛选
        for (ConditionsEntityExt conditionsEntityExt : conditionList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), StockFlowBillEnum.NAME.getAttr())) {
                params.put("productIdIn", conditionsEntityExt.getValue());
            } else if (Objects.equals(conditionsEntityExt.getAttr(), StockFlowBillEnum.WAREHOUSE_ID.getAttr())) {
                params.put("warehouseIdIn", conditionsEntityExt.getValue());
            }
        }
        // 日期筛选
        FiscalYearTimePojo fiscalYearTimePojo = formDataListDTO.getTimeFilter() == null ? new FiscalYearTimePojo() : formDataListDTO.getTimeFilter();
        // 财年开始月份，这里应该没有财年这个概念吧
        // int startMonth = companyConfigModel.getFiscalStartMonth(formDataListDTO.getCorpid());
        int startMonth = 1;
        fiscalYearTimePojo.setStartMonth(startMonth);
        Integer timeType = fiscalYearTimePojo.getTimeType4DefaultDay();
        TimeTypeEnum timeTypeEnum = TimeTypeEnum.getByCode(timeType);
        if (timeTypeEnum == null) {
            timeType = TimeTypeEnum.DAY.getCode();
        }
        fiscalYearTimePojo.setTimeTypeEnum(timeTypeEnum);
        Integer startTime = FiscalYearHelp.getStartTime(fiscalYearTimePojo, timeType, startMonth);
        Integer endTime = FiscalYearHelp.getEndTime(fiscalYearTimePojo, startTime, timeType, startMonth);
        // 台账分页信息
        List<StockFlowBillEntity> stockFlowBillList = stockFlowBillModel.findEntitys(params);
        if (stockFlowBillList.size() == 0) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        Integer count = stockFlowBillModel.getGroupByEntitysCount(params);
        paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(count));
        // 获取台账的期初数据
        Set<String> warehouseKeyList = new HashSet<>();
        warehouseKeyList.add("");
        stockFlowBillList.forEach(item -> warehouseKeyList.add(item.getWarehouseKey()));
        params.clear();
        params.put("corpid", corpid);
        params.put("del", 0);
        params.put("lessThanDate", startTime);
        params.put("orderByStr", " date desc, id desc");
        params.put("warehouseKeyIn", warehouseKeyList);
        List<StockFlowBillEntity> oriStockFlowBillList = stockFlowBillModel.getLatestFlowBillByWarehouseKey(params);
        Map<String, StockFlowBillEntity> oriStockMap = new HashMap<>(oriStockFlowBillList.size());
        oriStockFlowBillList.forEach(item -> oriStockMap.put(item.getWarehouseKey(), item));
        // 计算（期间入库，期初）, 期间出库
        params.clear();
        params.put("corpid", corpid);
        params.put("del", 0);
        params.put("greaterEqualThanDate", startTime);
        params.put("lessThanDate", endTime);
        params.put("groupByStr", "warehouse_key");
        params.put("warehouseKeyIn", warehouseKeyList);
        params.put("stockTypeIn", Arrays.asList(StockTypeEnum.IN_STOCK.getCode(), StockTypeEnum.ORI_STOCK.getCode()));
        List<StockFlowBillEntityExt> inStockList = stockFlowBillModel.getFlowInfo(params);
        params.remove("stockTypeIn");
        params.put("stockType", StockTypeEnum.ADJUST_STOCK.getCode());
        Map<String, StockFlowBillEntityExt> inStockMap = new HashMap<>(inStockList.size());
        inStockList.forEach(item -> inStockMap.put(item.getWarehouseKey(), item));
        // 兼容成本调整单
        Map<String, Object> costAdjustParams = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        costAdjustParams.putAll(params);
        costAdjustParams.remove("groupByStr");
        List<StockFlowBillEntity> entityEntitys = stockFlowBillModel.findEntitys(costAdjustParams);
        if (CollectionsUtil.isNotEmpty(entityEntitys)) {
            for (StockFlowBillEntity entityEntity : entityEntitys) {
                String warehouseKey = entityEntity.getWarehouseKey();
                if (inStockMap.containsKey(warehouseKey)) {
                    StockFlowBillEntityExt flowBill = inStockMap.get(warehouseKey);
                    flowBill.setTotalCost(Arith.add(entityEntity.getProductCost(), flowBill.getTotalCost()));
                } else {
                    StockFlowBillEntityExt stockFlowBillEntityExt = new StockFlowBillEntityExt();
                    stockFlowBillEntityExt.setTotalCost(entityEntity.getRemainingCost());
                    stockFlowBillEntityExt.setWarehouseKey(entityEntity.getWarehouseKey());
                    stockFlowBillEntityExt.setTotalNum(entityEntity.getRemainingStock());
                    inStockList.add(stockFlowBillEntityExt);
                }
            }
        }
        params.put("stockType", StockTypeEnum.OUT_STOCK.getCode());
        List<StockFlowBillEntityExt> outStockList = stockFlowBillModel.getFlowInfo(params);
        Map<String, StockFlowBillEntityExt> outStockMap = new HashMap<>(outStockList.size());
        outStockList.forEach(item -> outStockMap.put(item.getWarehouseKey(), item));
        // 这里会改变warehouseKeyList 筛选的时间段没有期初数据时，拿最新的结存数据处理
        warehouseKeyList.removeAll(oriStockMap.keySet());
        params.clear();
        params.put("corpid", corpid);
        params.put("del", 0);
        params.put("warehouseKeyIn", warehouseKeyList);
        List<StockSurplusRecordEntity> stockSurplusRecordList = stockSurplusRecordModel.getLatestFlowBillByWarehouseKey(params);
        Map<String, StockSurplusRecordEntity> oriStockSurplusMap = new HashMap<>(stockSurplusRecordList.size());
        stockSurplusRecordList.forEach(item -> oriStockSurplusMap.put(item.getWarehouseKey(), item));
        // 产品信息和仓库信息
        Set<Long> productIdSet = new HashSet<>();
        Set<Long> warehouseIdSet = new HashSet<>();
        stockFlowBillList.forEach(item -> {
            productIdSet.add(item.getProductId());
            warehouseIdSet.add(item.getWarehouseId());
        });
        List<PaasFormDataEntityExt> productEntityList = productService.getProductListById(productIdSet, corpid, DelEnum.NORMAL);
        params.clear();
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("idIn", warehouseIdSet);
        List<WarehouseEntityExt> warehouseEntityList = warehouseModel.findEntitys(params);
        Map<Long, WarehouseEntityExt> warehouseMap = new HashMap<>(warehouseEntityList.size());
        warehouseEntityList.forEach(item -> warehouseMap.put(item.getId(), item));
        productService.formatChildSpecification(productEntityList, corpid);
        Map<Long, String> categoryMap = productListHelp.categoryList(formDataListDTO.getCorpid());
        productEntityList.forEach(item -> {
            Long categoryId = item.getData().getLong(ProductEnum.CATEGORY_ID.getAttr());
            item.getData().put(ProductEnum.CATEGORY_ID.getAttr(), categoryMap.getOrDefault(categoryId, ""));
        });
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(productEntityList.size());
        productEntityList.forEach(item -> productMap.put(item.getDataId(), item));
        // 列表数据封装
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>(stockFlowBillList.size());
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setLoginUser(formDataListDTO.getLoginUser());
        handlerExplainDTO.setUserId(formDataListDTO.getLoginUser().getUserId());
        PaasFormExplainEntity productExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        Map<String, FieldAttrEntity> productExplainMap = ExplainUtil.getExplainMap(productExplainEntity.getExplains(), null);
        // 产品成本权限
        FieldAttrEntity costFieldPojo = productExplainMap.get(ProductEnum.COST.getAttr());
        boolean costVisible = Objects.equals(costFieldPojo.getVisible(), 1) && !ExplainUtil.invisibleOfScope(costFieldPojo, handlerExplainDTO);
        boolean isAmount = Objects.equals(costFieldPojo.getAmountFlag(), 1);
        Integer costAccuracy = costFieldPojo.getAccuracy();
        // 库存数量精度
        FieldAttrEntity stockField = productExplainMap.get(ProductEnum.STOCK.getAttr());
        Integer stockAccuracy = stockField.getAccuracy();
        // 单位解释
        FieldAttrEntity unitFieldPojo = productExplainMap.get(ProductEnum.UNIT.getAttr());
        // 高级权限样式
        String invisibleStyle = StringConstant.INVISIBLE_VALUE;
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (!notExport) {
            invisibleStyle = null;
        }
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        for (StockFlowBillEntity stockFlowBillEntity : stockFlowBillList) {
            Long productId = stockFlowBillEntity.getProductId();
            Long warehouseId = stockFlowBillEntity.getWarehouseId();
            String warehouseKey = stockFlowBillEntity.getWarehouseKey();
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            JSONObject data = new JSONObject();
            // 产品信息封装
            if (productMap.containsKey(productId)) {
                PaasFormDataEntityExt product = productMap.get(productId);
                paasFormDataEntityExt.setDataId(product.getDataId());
                JSONObject productObj = product.getData();
                data.put(StockStandingBookEnum.SERIALNO.getAttr(), product.getSerialNo());
                data.put(StockStandingBookEnum.NAME.getAttr(), productObj.getString(ProductEnum.NAME.getAttr()));
                data.put(StockStandingBookEnum.SPECIFICATION.getAttr(), productObj.getString(ProductEnum.SPECIFICATION.getAttr()));
                data.put(StockStandingBookEnum.CATEGORY_ID.getAttr(), productObj.getString(ProductEnum.CATEGORY_ID.getAttr()));
                String unitStr = FastJsonHelper.getStringOrDefaultFromFormData(productObj, ProductEnum.UNIT.getAttr(), "");
                String unit = "";
                // 多单位
                if (BasicConstant.ONE.equals(productObj.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr())) && StringUtil.isNotEmpty(unitStr)) {
                    data.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), data.getLongValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                    MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(Long.parseLong(unitStr));
                    unit = multiUnitItemPoJo.getBaseName();
                } else {
                    unit = fieldAttrHelp.getDataDictionaryTextByValue(unitStr, unitFieldPojo);
                }
                data.put(StockFlowBillEnum.UNIT.getAttr(), unit);
                if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                    data.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), productObj.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()));
                }
            }
            // 仓库信息封装
            if (warehouseMap.containsKey(warehouseId)) {
                WarehouseEntityExt warehouse = warehouseMap.get(warehouseId);
                JSONObject warehouseObj = warehouse.getData();
                data.put(StockStandingBookEnum.WAREHOUSE_ID.getAttr(), warehouseObj.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
            }
            Double remainNum = 0D;
            Double remainCost = 0D;
            // 期初数据
            if (oriStockMap.containsKey(warehouseKey)) {
                JSONArray oriArray = new JSONArray();
                JSONObject oriObject = new JSONObject();
                remainNum = oriStockMap.get(warehouseKey).getRemainingStock();
                remainCost = oriStockMap.get(warehouseKey).getRemainingCost();
                Double oriStock = attrDecimalPrecisionHelper.setPrecision(remainNum, stockAccuracy);
                Object oriCost;
                if (isAmount) {
                    oriCost = AttrDecimalPrecisionHelper.parseThousandth(remainCost, costAccuracy);
                } else {
                    oriCost = attrDecimalPrecisionHelper.setPrecision(remainCost, costAccuracy);
                }
                oriObject.put("num_1", oriStock);
                if (costVisible) {
                    if (!Objects.equals(oriStock, 0D)) {
                        if (isAmount) {
                            oriObject.put("num_2", AttrDecimalPrecisionHelper.parseThousandth(Arith.div(Arith.round(remainCost, costAccuracy), oriStock), costAccuracy));
                        } else {
                            oriObject.put("num_2", attrDecimalPrecisionHelper.setPrecision(Arith.div(Arith.round(remainCost, costAccuracy), oriStock), costAccuracy));
                        }
                    } else {
                        if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                            oriObject.put("num_2", "");
                        }
                    }
                    oriObject.put("num_3", oriCost);
                } else {
                    oriObject.put("num_2", invisibleStyle);
                    oriObject.put("num_3", invisibleStyle);
                }
                oriArray.add(oriObject);
                data.put(StockStandingBookEnum.ORI_STOCK.getAttr(), oriArray);
            } else if (oriStockSurplusMap.containsKey(warehouseKey)) {
                // 期初的问题
                JSONArray oriArray = new JSONArray();
                JSONObject oriObject = new JSONObject();
                remainNum = oriStockSurplusMap.get(warehouseKey).getRemainingStock();
                remainCost = oriStockSurplusMap.get(warehouseKey).getRemainingCost();
                Double oriStock = attrDecimalPrecisionHelper.setPrecision(remainNum, stockAccuracy);
                Object oriCost;
                if (isAmount) {
                    oriCost = AttrDecimalPrecisionHelper.parseThousandth(remainCost, costAccuracy);
                } else {
                    oriCost = attrDecimalPrecisionHelper.setPrecision(remainCost, costAccuracy);
                }
                oriObject.put("num_1", oriStock);
                if (costVisible) {
                    if (!Objects.equals(oriStock, 0D)) {
                        if (isAmount) {
                            oriObject.put("num_2", AttrDecimalPrecisionHelper.parseThousandth(Arith.div(Arith.round(remainCost, costAccuracy), oriStock), costAccuracy));
                        } else {
                            oriObject.put("num_2", attrDecimalPrecisionHelper.setPrecision(Arith.div(Arith.round(remainCost, costAccuracy), oriStock), costAccuracy));
                        }
                    } else {
                        if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                            oriObject.put("num_2", "");
                        }
                    }
                    oriObject.put("num_3", oriCost);
                } else {
                    oriObject.put("num_2", invisibleStyle);
                    oriObject.put("num_3", invisibleStyle);
                }
                oriArray.add(oriObject);
                data.put(StockStandingBookEnum.ORI_STOCK.getAttr(), oriArray);
            }
            // 入库数据
            if (inStockMap.containsKey(warehouseKey)) {
                JSONArray inArray = new JSONArray();
                JSONObject inObject = new JSONObject();
                Double inStockCost = inStockMap.get(warehouseKey).getTotalCost();
                Double inStockNum = attrDecimalPrecisionHelper.setPrecision(inStockMap.get(warehouseKey).getTotalNum(), stockAccuracy);
                Object inStockCostObj;
                if (isAmount) {
                    inStockCostObj = AttrDecimalPrecisionHelper.parseThousandth(inStockCost, costAccuracy);
                } else {
                    inStockCostObj = attrDecimalPrecisionHelper.setPrecision(inStockCost, costAccuracy);
                }
                remainCost = Arith.add(inStockCost, remainCost);
                remainNum = Arith.add(inStockNum, remainNum);
                inObject.put("num_1", inStockNum);
                if (costVisible) {
                    inObject.put("num_2", inStockCostObj);
                } else {
                    inObject.put("num_2", invisibleStyle);
                }
                inArray.add(inObject);
                data.put(StockStandingBookEnum.PERIOD_INSTOCK.getAttr(), inArray);
            }
            // 出库数据
            if (outStockMap.containsKey(warehouseKey)) {
                JSONArray outArray = new JSONArray();
                JSONObject outObject = new JSONObject();
                Double outStockNum = attrDecimalPrecisionHelper.setPrecision(outStockMap.get(warehouseKey).getTotalNum(), stockAccuracy);
                Double outStockCost = outStockMap.get(warehouseKey).getTotalCost();
                Object outStockCostObj;
                if (isAmount) {
                    outStockCostObj = AttrDecimalPrecisionHelper.parseThousandth(outStockCost, costAccuracy);
                } else {
                    outStockCostObj = attrDecimalPrecisionHelper.setPrecision(outStockCost, costAccuracy);
                }
                remainNum = Arith.sub(remainNum, outStockNum);
                remainCost = Arith.sub(remainCost, outStockCost);
                outObject.put("num_1", outStockNum);
                if (costVisible) {
                    outObject.put("num_2", outStockCostObj);
                } else {
                    outObject.put("num_2", invisibleStyle);
                }
                outArray.add(outObject);
                data.put(StockStandingBookEnum.PERIOD_OUTSTOCK.getAttr(), outArray);
            }
            // 结存数据
            JSONArray remainArray = new JSONArray();
            JSONObject remainObject = new JSONObject();
            remainObject.put("num_1", attrDecimalPrecisionHelper.setPrecision(remainNum, stockAccuracy));
            if (costVisible) {
                if (!Objects.equals(remainNum, 0D)) {
                    if (isAmount) {
                        remainObject.put("num_2", AttrDecimalPrecisionHelper.parseThousandth(Arith.div(remainCost, remainNum), costAccuracy));
                    } else {
                        remainObject.put("num_2", attrDecimalPrecisionHelper.setPrecision(Arith.div(remainCost, remainNum), costAccuracy));
                    }
                } else {
                    if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                        remainObject.put("num_2", "");
                    }
                }
                if (isAmount) {
                    remainObject.put("num_3", AttrDecimalPrecisionHelper.parseThousandth(remainCost, costAccuracy));
                } else {
                    remainObject.put("num_3", attrDecimalPrecisionHelper.setPrecision(remainCost, costAccuracy));
                }
            } else {
                remainObject.put("num_2", invisibleStyle);
                remainObject.put("num_3", invisibleStyle);
            }
            remainArray.add(remainObject);
            data.put(StockStandingBookEnum.REMAINING_STOCK.getAttr(), remainArray);
            paasFormDataEntityExt.setData(data);
            paasFormDataESList.add(paasFormDataEntityExt);
        }
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        return paasFormDataEsListVO;
    }

    /**
     * 回款计划列表
     *
     * @param paymentTaskExportDTO
     * @return
     */
    @Override
    public PaasFormDataEsListVO paymentTaskExport(PaymentTaskExportDTO paymentTaskExportDTO) throws XbbException {
        PaymentTaskGetDTO paymentTaskGetDTO = new PaymentTaskGetDTO();
        BeanUtil.copyProperties(paymentTaskExportDTO, paymentTaskGetDTO);
        List<ConditionsEntityExt> conditionsEntityExtList = paymentTaskService.setConditionList(paymentTaskGetDTO);
        paymentTaskService.setTeamCondition(paymentTaskGetDTO, conditionsEntityExtList);
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,null,paymentTaskExportDTO.getCorpid(),XbbRefTypeEnum.PAYMENT_TASK.getCode());
        boolQueryBuilder.filter(termQuery("corpid.keyword",  paymentTaskExportDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.FORMID, paymentTaskExportDTO.getFormId()));
        List<PaasFormDataEntityExt> planList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT_TASK, boolQueryBuilder, PaasFormDataEntityExt.class, null);
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        paasFormDataEsListVO.setPaasFormDataESList(planList);
        PaasFormExplainEntity planExplain = paasFormExplainModel.getByBusinessType4Distributor(XbbRefTypeEnum.PAYMENT_TASK.getCode(), paymentTaskExportDTO.getCorpid(), paymentTaskExportDTO.getDistributorMark());
        if (Objects.isNull(planExplain)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(planExplain.getExplains(), null);
        paasFormDataEsListVO.setExplainMap(explainMap);
        return paasFormDataEsListVO;
    }

    /**
     *查询回款计划列表
     *
     * @param paymentTaskGetDTO
     * @return
     */
    @Override
    public PaasFormDataEsListVO paymentTaskList(PaymentTaskGetDTO paymentTaskGetDTO) throws XbbException {
        Integer businessType = paymentTaskGetDTO.getBusinessType();
        if (Objects.isNull(businessType)) {
            businessType = paymentTaskGetDTO.getSubBusinessType();
        }
        if (businessType == null || !Objects.equals(businessType,XbbRefTypeEnum.PAYMENT_TASK.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionsEntityExtList = paymentTaskService.setConditionList(paymentTaskGetDTO);
        paymentTaskService.setTeamCondition(paymentTaskGetDTO,conditionsEntityExtList);
        if (ObjectUtils.isEmpty(paymentTaskGetDTO.getOperateType()) || PaymentTaskConstant.PAYMENT_TASK_THROUGH != paymentTaskGetDTO.getOperateType()) {
            List<ConditionsEntityExt> dateCondition = paymentTaskService.getReturnDateCondition(paymentTaskGetDTO);
            conditionsEntityExtList.addAll(dateCondition);
        }
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(paymentTaskGetDTO, formDataListDTO);
        formDataListDTO.setConditions(conditionsEntityExtList);
        // 回款计划列表按照执行时间升序
        Map<String, String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        sortMap.put("field", PaymentTaskEnum.EXECUTOR_TIME.getAttr());
        sortMap.put("sort", "asc");
        formDataListDTO.setSortMap(sortMap);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO productSerialList(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions();
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();

        ListGroupEnum listGroupEnum;
        // 参数缺少分组id时，默认为全部分组
        if (formDataListDTO.getListGroupId() == null) {
            listGroupEnum =  ListGroupEnum.SEQ_SEARCH;
        } else {
            listGroupEnum = ListGroupEnum.getByCode(formDataListDTO.getListGroupId().intValue());
        }
        Integer page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();


        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(businessType, corpid);
        paasFormDataEsListVO.setForm(paasFormEntityExt);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(businessType, corpid);
        if (Objects.isNull(paasFormExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        // 解释处理
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        explainList.forEach(item -> {
            item.setDisableListSort(1);
            item.setEditable(0);
            if (ProductSerialBalanceEnum.SHEET_NO.getAttr().equals(item.getAttr())) {
                item.setVisible(0);
            }
        });
        explainList.removeIf(item -> Objects.equals(item.getAttr(), ProductSerialBalanceEnum.SHEET_NO.getAttr()));
        paasFormDataEsListVO.setHeadList(explainList);
        paasFormDataEsListVO.setBusinessType(formDataListDTO.getBusinessType());
        formDataListSearchHelp.setButtons(formDataListDTO, paasFormDataEsListVO);
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, paasFormDataEsListVO);
        // 查看权限，没有则返回空列表
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!permSet.contains(ProPermissionAliasEnum.SEQ_SEARCH_VIEW.getAlias())) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        // 查询条件
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("start", (long)(page - 1) * pageSize);
        params.put("pageNum", pageSize);
        params.put("visible", 1);
        if (Objects.equals(listGroupEnum, ListGroupEnum.SEQ_SEARCH_INSTOCK)) {
            params.put(StringConstant.STATUS, SerialStatusEnum.IN_STOCK.getCode());
        } else if (Objects.equals(listGroupEnum, ListGroupEnum.SEQ_SEARCH_OUTSTOCK)) {
            params.put(StringConstant.STATUS, SerialStatusEnum.OUT_STOCK.getCode());
        }
        // 产品筛选和仓库筛选
        for (ConditionsEntityExt conditionsEntityExt : conditionList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), ProductSerialBalanceEnum.SEQ.getAttr())) {
                params.put("seq", conditionsEntityExt.getValue().get(0));
            } else if (Objects.equals(conditionsEntityExt.getAttr(), ProductSerialBalanceEnum.WAREHOUSE_ID.getAttr())) {
                // 马雄说，出库分组仓库筛选无效
                if (!Objects.equals(listGroupEnum, ListGroupEnum.SEQ_SEARCH_OUTSTOCK)) {
                    params.put("warehouseIdIn", conditionsEntityExt.getValue());
                }
            } else if (Objects.equals(conditionsEntityExt.getAttr(), ProductSerialBalanceEnum.NAME.getAttr())) {
                params.put("productIdIn", conditionsEntityExt.getValue());
            }
        }
        if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue()) && StringUtil.isNotEmpty(formDataListDTO.getNameLike())) {
            params.put("seq", formDataListDTO.getNameLike());
        }
        List<ProductSerialBalanceEntity> productSerialBalanceEntityList = productSerialBalanceModel.findEntitys(params);
        paasFormDataEsListVO.setBottomPermissions(new ArrayList<>());
        if (productSerialBalanceEntityList.size() == 0) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        Integer count = productSerialBalanceModel.getEntitysCount(params);
        paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(count));
        // 产品信息和仓库信息
        Set<Long> productIdSet = new HashSet<>();
        Set<Long> warehouseIdSet = new HashSet<>();
        productSerialBalanceEntityList.forEach(item -> {
            productIdSet.add(item.getProductId());
            warehouseIdSet.add(item.getWarehouseId());
        });
        List<PaasFormDataEntityExt> productEntityList = productService.getProductListById(productIdSet, corpid, DelEnum.NORMAL);
        params.clear();
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("idIn", warehouseIdSet);
        List<WarehouseEntityExt> warehouseEntityList = warehouseModel.findEntitys(params);
        Map<Long, WarehouseEntityExt> warehouseMap = new HashMap<>(warehouseEntityList.size());
        warehouseEntityList.forEach(item -> warehouseMap.put(item.getId(), item));
        productService.formatChildSpecification(productEntityList, corpid);
        Map<Long, String> categoryMap = productListHelp.categoryList(formDataListDTO.getCorpid());
        productEntityList.forEach(item -> {
            Long categoryId = item.getData().getLong(ProductEnum.CATEGORY_ID.getAttr());
            item.getData().put(ProductEnum.CATEGORY_ID.getAttr(), categoryMap.getOrDefault(categoryId, ""));
        });
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(productEntityList.size());
        productEntityList.forEach(item -> productMap.put(item.getDataId(), item));
        // 列表数据封装
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>(productSerialBalanceEntityList.size());
        for (ProductSerialBalanceEntity serialBalanceEntity : productSerialBalanceEntityList) {
            long productId = serialBalanceEntity.getProductId();
            Long warehouseId = serialBalanceEntity.getWarehouseId();
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setDataId(serialBalanceEntity.getId());
            JSONObject data = new JSONObject();
            // 产品信息封装
            if (productMap.containsKey(productId)) {
                PaasFormDataEntityExt product = productMap.get(productId);
                JSONObject productObj = product.getData();
                data.put(ProductSerialBalanceEnum.SERIALNO.getAttr(), product.getSerialNo());
                data.put(ProductSerialBalanceEnum.NAME.getAttr(), productObj.getString(ProductEnum.NAME.getAttr()));
                data.put(ProductSerialBalanceEnum.SPECIFICATION.getAttr(), productObj.getString(ProductEnum.SPECIFICATION.getAttr()));
            }
            // 仓库信息封装
            if (warehouseMap.containsKey(warehouseId)) {
                WarehouseEntityExt warehouse = warehouseMap.get(warehouseId);
                JSONObject warehouseObj = warehouse.getData();
                if (Objects.equals(SerialStatusEnum.OUT_STOCK.getCode(), serialBalanceEntity.getStatus())) {
                    data.put(ProductSerialBalanceEnum.WAREHOUSE_ID.getAttr(), "--");
                } else {
                    data.put(ProductSerialBalanceEnum.WAREHOUSE_ID.getAttr(), warehouseObj.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
                }
            }
            // 其他基础信息封装
            boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
            if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue()) || !notExport) {
                data.put(StockFlowBillEnum.SHEET_NO.getAttr(), serialBalanceEntity.getRefSheetNo());
                data.put(StockFlowBillEnum.TIME.getAttr(), DateTimeUtil.getStringEpochSecond(serialBalanceEntity.getDate(), DateTimeUtil.SDFYMDHM));
            } else {
                JSONArray sheetArray = new JSONArray();
                JSONObject sheetObject = new JSONObject();
                sheetObject.put("name", serialBalanceEntity.getRefSheetNo());
                sheetObject.put("id", serialBalanceEntity.getRefId());
                sheetObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
                sheetObject.put("businessType", serialBalanceEntity.getBusinessType());
                sheetArray.add(sheetObject);
                data.put(StockFlowBillEnum.SHEET_NO.getAttr(), sheetArray);
                data.put(StockFlowBillEnum.TIME.getAttr(), serialBalanceEntity.getDate());
            }
            data.put(ProductSerialBalanceEnum.BUSINESS_TYPE.getAttr(), XbbRefTypeEnum.getByCode(serialBalanceEntity.getBusinessType()).getName());
            data.put(ProductSerialBalanceEnum.BUSINESS_ID.getAttr(), serialBalanceEntity.getBusinessName());
            data.put(ProductSerialBalanceEnum.MEMO.getAttr(), serialBalanceEntity.getMemo());
            data.put(ProductSerialBalanceEnum.SEQ.getAttr(), serialBalanceEntity.getSeq());
            data.put(ProductSerialBalanceEnum.STATUS.getAttr(), Objects.requireNonNull(SerialStatusEnum.getByCode(serialBalanceEntity.getStatus())).getName());

            paasFormDataEntityExt.setData(data);
            paasFormDataEntityExt.setRefProductId(productId);
            paasFormDataESList.add(paasFormDataEntityExt);
        }
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        // 设置操作方式
        AbstractOptionHandle abstractOptionHandle = optionFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        abstractOptionHandle.setOptionsInExplain(formDataListDTO, explainList, paasFormDataEsListVO);
        abstractOptionHandle.setOptionsInData(formDataListDTO, paasFormDataEsListVO);

        // 列表排序
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        //列冻结和列隐藏
        formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, paasFormDataEsListVO);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO batchFlowBillList(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions();
        String corpid = formDataListDTO.getCorpid();
        Long formId = formDataListDTO.getFormId();
        int page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();
        // 查询表单，解释
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        paasFormDataEsListVO.setForm(paasFormEntityExt);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        // 解释处理
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        explainList.forEach(item -> {
            item.setDisableListSort(1);
            item.setEditable(0);
        });
        paasFormDataEsListVO.setHeadList(explainList);
        paasFormDataEsListVO.setBusinessType(formDataListDTO.getBusinessType());
        formDataListSearchHelp.setButtons(formDataListDTO, paasFormDataEsListVO);
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        //列隐藏和列冻结
        formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, paasFormDataEsListVO);
        // 查看权限，没有则返回空列表
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!permSet.contains(ProPermissionAliasEnum.BATCH_FLOW_BILL_VIEW.getAlias())) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        // 仓库权限
        List<Long> warehouseIdList = warehouseService.getWarehouseIdsByPermission(formDataListDTO.getLoginUser(), formDataListDTO.getLoginUser().getDepSet());
        // 查询条件
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("visible", 1);
        params.put("start", (page - 1) * pageSize);
        params.put("pageNum", pageSize);
        params.put("warehouseIdIn", warehouseIdList);
        // 需要取交集的动作，难顶
        List<Integer> businessTypeList = new ArrayList<>();
        boolean hasBusinessType = false;
        // 产品筛选和仓库筛选
        for (ConditionsEntityExt conditionsEntityExt : conditionList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), BatchFlowBillEnum.NAME.getAttr())) {
                params.put("productIdIn", conditionsEntityExt.getValue());
            } else if (Objects.equals(conditionsEntityExt.getAttr(), BatchFlowBillEnum.WAREHOUSE_ID.getAttr())) {
                params.put("warehouseIdIn", conditionsEntityExt.getValue());
            } else if (Objects.equals(conditionsEntityExt.getAttr(), BatchFlowBillEnum.TYPE.getAttr())) {
                params.put("businessTypeIn", conditionsEntityExt.getValue());
            } else if (Objects.equals(conditionsEntityExt.getAttr(), BatchFlowBillEnum.BUSINESS_ID.getAttr()) && Objects.nonNull(conditionsEntityExt.getValue()) && !conditionsEntityExt.getValue().isEmpty()) {
                StockFilterTypeEnum stockFilterTypeEnum = StockFilterTypeEnum.getByAttr(conditionsEntityExt.getSubAttr());
                if (Objects.nonNull(stockFilterTypeEnum)) {
                    params.put("businessId", conditionsEntityExt.getValue().get(0));
                    hasBusinessType = true;
                    if (businessTypeList.isEmpty()) {
                        businessTypeList.addAll(stockFilterTypeEnum.getBusinessTypeList());
                    } else {
                        businessTypeList.retainAll(stockFilterTypeEnum.getBusinessTypeList());
                    }
                }
            } else if (Objects.equals(conditionsEntityExt.getAttr(), BatchFlowBillEnum.BATCH.getAttr()) && CollectionUtils.isNotEmpty(conditionsEntityExt.getValue())) {
                params.put("batch", conditionsEntityExt.getValue().get(0));
            }
        }
        // 常用筛选 单据编号和往来单位
        JSONObject commonFilter = formDataListDTO.getCommonFilter();
        if (Objects.nonNull(commonFilter) && !commonFilter.isEmpty()) {
            if (Objects.nonNull(commonFilter.getJSONObject(FieldTypeEnum.REF_ID.getAlias())) && StringUtil.isNotEmpty(commonFilter.getJSONObject(FieldTypeEnum.REF_ID.getAlias()).getString("value"))) {
                StockFilterTypeEnum stockFilterTypeEnum = StockFilterTypeEnum.getByAttr(commonFilter.getJSONObject(FieldTypeEnum.REF_ID.getAlias()).getString("attr"));
                params.put("refId", commonFilter.getJSONObject(FieldTypeEnum.REF_ID.getAlias()).getLong("value"));
                hasBusinessType = true;
                if (businessTypeList.isEmpty()) {
                    businessTypeList.addAll(stockFilterTypeEnum.getBusinessTypeList());
                } else {
                    businessTypeList.retainAll(stockFilterTypeEnum.getBusinessTypeList());
                }
            } else if (Objects.nonNull(commonFilter.getJSONObject(FieldTypeEnum.BUSINESS_ID.getAlias())) && StringUtil.isNotEmpty(commonFilter.getJSONObject(FieldTypeEnum.BUSINESS_ID.getAlias()).getString("value"))) {
                StockFilterTypeEnum stockFilterTypeEnum = StockFilterTypeEnum.getByAttr(commonFilter.getJSONObject(FieldTypeEnum.BUSINESS_ID.getAlias()).getString("attr"));
                if (Objects.nonNull(stockFilterTypeEnum)) {
                    params.put("businessId", commonFilter.getJSONObject(FieldTypeEnum.BUSINESS_ID.getAlias()).getLong("value"));
                    hasBusinessType = true;
                    if (businessTypeList.isEmpty()) {
                        businessTypeList.addAll(stockFilterTypeEnum.getBusinessTypeList());
                    } else {
                        businessTypeList.retainAll(stockFilterTypeEnum.getBusinessTypeList());
                    }
                }
            }
        }
        if (hasBusinessType) {
            businessTypeList.add(-1);
            params.put("businessTypeIn", businessTypeList);
        }
        // 日期筛选
        FiscalYearTimePojo fiscalYearTimePojo = formDataListDTO.getTimeFilter() == null ? new FiscalYearTimePojo() : formDataListDTO.getTimeFilter();
        String batchLike = formDataListDTO.getNameLike();
        if (StringUtil.isNotEmpty(batchLike)) {
            params.put("batchLike", batchLike);
        }
        int startMonth = 1;
        fiscalYearTimePojo.setStartMonth(startMonth);
        Integer timeType = fiscalYearTimePojo.getTimeType4DefaultDay();
        TimeTypeEnum timeTypeEnum = TimeTypeEnum.getByCode(timeType);
        if (timeTypeEnum == null) {
            timeType = TimeTypeEnum.DAY.getCode();
        }
        fiscalYearTimePojo.setTimeTypeEnum(timeTypeEnum);
        Integer startTime = FiscalYearHelp.getStartTime(fiscalYearTimePojo, timeType, startMonth);
        Integer endTime = FiscalYearHelp.getEndTime(fiscalYearTimePojo, startTime, timeType, startMonth);
        params.put("greaterEqualThanDate", startTime);
        params.put("lessThanDate", endTime);
        String orderByStr = " date asc, id asc";
        if (Objects.nonNull(formDataListDTO.getSortMap())) {
            if(SortOrder.DESC.toString().equals(formDataListDTO.getSortMap().get("sort"))){
                orderByStr = " date desc, id desc";
            }
        }
        params.put("orderByStr", orderByStr);
        params.put("page", formDataListDTO.getPage());
        // 流水分页信息
        PageHelper pageHelper = PageHelperUtil.getPageHelper(params, batchFlowBillModel, pageSize);
        List<BatchFlowBillEntity> batchFlowBillEntityList = (List<BatchFlowBillEntity>) PageHelperUtil.getEntityList(params, pageHelper, batchFlowBillModel);
        paasFormDataEsListVO.setPageHelper(pageHelper);
        // 产品信息和仓库信息
        Set<Long> productIdSet = new HashSet<>();
        Set<Long> warehouseIdSet = new HashSet<>();
        batchFlowBillEntityList.forEach(item -> {
            productIdSet.add(item.getProductId());
            warehouseIdSet.add(item.getWarehouseId());
        });
        List<PaasFormDataEntityExt> productEntityList = productService.getProductListById(productIdSet, corpid, DelEnum.NORMAL);
        params.clear();
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("idIn", warehouseIdSet);
        List<WarehouseEntityExt> warehouseEntityList = warehouseModel.findEntitys(params);
        Map<Long, WarehouseEntityExt> warehouseMap = new HashMap<>(warehouseEntityList.size());
        warehouseEntityList.forEach(item -> warehouseMap.put(item.getId(), item));
        productService.formatChildSpecification(productEntityList, corpid);
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(productEntityList.size());
        productEntityList.forEach(item -> productMap.put(item.getDataId(), item));
        // 列表数据封装
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>(batchFlowBillEntityList.size());
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setLoginUser(formDataListDTO.getLoginUser());
        handlerExplainDTO.setUserId(formDataListDTO.getLoginUser().getUserId());
        PaasFormExplainEntity productExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        Map<String, FieldAttrEntity> productExplainMap = ExplainUtil.getExplainMap(productExplainEntity.getExplains(), null);
        // 产品成本权限
        FieldAttrEntity costFieldPojo = productExplainMap.get(ProductEnum.COST.getAttr());
        boolean costVisible = Objects.equals(costFieldPojo.getVisible(), 1) && !ExplainUtil.invisibleOfScope(costFieldPojo, handlerExplainDTO);
        boolean isAmount = Objects.equals(costFieldPojo.getAmountFlag(), 1);
        Integer costAccuracy = costFieldPojo.getAccuracy();
        // 库存数量精度
        FieldAttrEntity stockField = productExplainMap.get(ProductEnum.STOCK.getAttr());
        Integer stockAccuracy = stockField.getAccuracy();
        // 单位解释
        FieldAttrEntity unitFieldPojo = productExplainMap.get(ProductEnum.UNIT.getAttr());
        // 高级权限样式
        String invisibleStyle = StringConstant.INVISIBLE_VALUE;
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (!notExport) {
            invisibleStyle = null;
        }
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        for (BatchFlowBillEntity batchFlowBillEntity : batchFlowBillEntityList) {
            Long productId = batchFlowBillEntity.getProductId();
            Long warehouseId = batchFlowBillEntity.getWarehouseId();
            boolean isOutStock = Objects.equals(batchFlowBillEntity.getStockType(), 2);
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setDataId(batchFlowBillEntity.getId());
            JSONObject data = new JSONObject();
            // 产品信息封装
            if (productMap.containsKey(productId)) {
                PaasFormDataEntityExt product = productMap.get(productId);
                JSONObject productObj = product.getData();
                data.put(BatchFlowBillEnum.SERIAL_NO.getAttr(), product.getSerialNo());
                data.put(BatchFlowBillEnum.NAME.getAttr(), productObj.getString(ProductEnum.NAME.getAttr()));
                data.put(BatchFlowBillEnum.SPECIFICATION.getAttr(), productObj.getString(ProductEnum.SPECIFICATION.getAttr()));
                String unitStr = FastJsonHelper.getStringOrDefaultFromFormData(productObj, ProductEnum.UNIT.getAttr(), "");
                String unit = "";
                // 多单位
                if (BasicConstant.ONE.equals(productObj.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr())) && StringUtil.isNotEmpty(unitStr)) {
                    data.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), data.getLongValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                    MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(Long.parseLong(unitStr));
                    unit = multiUnitItemPoJo.getBaseName();
                } else {
                    unit = fieldAttrHelp.getDataDictionaryTextByValue(unitStr, unitFieldPojo);
                }
                data.put(StockFlowBillEnum.UNIT.getAttr(), unit);
                if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                    data.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), productObj.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()));
                }
            }
            // 仓库信息封装
            if (warehouseMap.containsKey(warehouseId)) {
                WarehouseEntityExt warehouse = warehouseMap.get(warehouseId);
                JSONObject warehouseObj = warehouse.getData();
                data.put(BatchFlowBillEnum.WAREHOUSE_ID.getAttr(), warehouseObj.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
            }
            // 其他基础信息封装
            if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue()) || !notExport) {
                data.put(BatchFlowBillEnum.SHEET_NO.getAttr(), batchFlowBillEntity.getRefSheetNo());
                data.put(BatchFlowBillEnum.TIME.getAttr(), DateTimeUtil.getStringEpochSecond(batchFlowBillEntity.getDate(), DateTimeUtil.SDFDate));
                data.put(BatchFlowBillEnum.PRODUCE_DATE.getAttr(), DateTimeUtil.getStringEpochSecond(batchFlowBillEntity.getProduceDate(), DateTimeUtil.SDFDate));
                data.put(BatchFlowBillEnum.EXPIRE_DATE.getAttr(), DateTimeUtil.getStringEpochSecond(batchFlowBillEntity.getExpireDate(), DateTimeUtil.SDFDate));
                data.put(BatchFlowBillEnum.TYPE.getAttr(), XbbRefTypeEnum.getByCode(batchFlowBillEntity.getBusinessType()).getName());
            } else {
                JSONArray sheetArray = new JSONArray();
                JSONObject sheetObject = new JSONObject();
                sheetObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
                sheetObject.put("name", batchFlowBillEntity.getRefSheetNo());
                // 期初穿透仓库详情页
                if (Objects.equals(batchFlowBillEntity.getBusinessType(), XbbRefTypeEnum.ORI_STOCK.getCode())) {
                    sheetObject.put("id", warehouseId);
                    sheetObject.put("businessType", XbbRefTypeEnum.WAREHOUSE.getCode());
                } else {
                    sheetObject.put("id", batchFlowBillEntity.getRefId());
                    sheetObject.put("businessType", batchFlowBillEntity.getBusinessType());
                }
                sheetArray.add(sheetObject);
                data.put(BatchFlowBillEnum.SHEET_NO.getAttr(), sheetArray);
                data.put(BatchFlowBillEnum.TIME.getAttr(), batchFlowBillEntity.getDate());
                data.put(BatchFlowBillEnum.PRODUCE_DATE.getAttr(), batchFlowBillEntity.getProduceDate());
                data.put(BatchFlowBillEnum.EXPIRE_DATE.getAttr(), batchFlowBillEntity.getExpireDate());
                data.put(BatchFlowBillEnum.TYPE.getAttr(), new ItemPoJo(XbbRefTypeEnum.getByCode(batchFlowBillEntity.getBusinessType()).getName(), null, false, null));
            }
            if (Objects.nonNull(batchFlowBillEntity.getGuaranteePeriod()) && !Objects.equals(batchFlowBillEntity.getProduceDate(), 0L)) {
                data.put(BatchFlowBillEnum.GUARANTEE_PERIOD.getAttr(), batchFlowBillEntity.getGuaranteePeriod()/ TimeConstant.SECONDS_PER_DAY);
            }
            data.put(BatchFlowBillEnum.BUSINESS_ID.getAttr(), batchFlowBillEntity.getBusinessName());
            data.put(BatchFlowBillEnum.BATCH.getAttr(), batchFlowBillEntity.getBatch());

            // 出入库数据封装
            JSONArray outInArray = new JSONArray();
            JSONObject outInObject = new JSONObject();
            Double productNum = attrDecimalPrecisionHelper.setPrecision(batchFlowBillEntity.getNum(), stockAccuracy);
            Double remainingStock = attrDecimalPrecisionHelper.setPrecision(batchFlowBillEntity.getRemainingStock(), stockAccuracy);
            Object productCost;
            Object remainingCost;
            if (isAmount) {
                productCost = AttrDecimalPrecisionHelper.parseThousandth(batchFlowBillEntity.getProductCost(), costAccuracy);
                remainingCost = AttrDecimalPrecisionHelper.parseThousandth(batchFlowBillEntity.getRemainingCost(), costAccuracy);
            } else {
                productCost = attrDecimalPrecisionHelper.setPrecision(batchFlowBillEntity.getProductCost(), costAccuracy);
                remainingCost = attrDecimalPrecisionHelper.setPrecision(batchFlowBillEntity.getRemainingCost(), costAccuracy);
            }
            if (isOutStock) {
                outInObject.put(FlowSubFormEnum.QUANTITY.getAttr(), "-" + AttrDecimalPrecisionHelper.setPrecisionStr(productNum.toString(), stockAccuracy));
            } else {
                outInObject.put(FlowSubFormEnum.QUANTITY.getAttr(), "+" + AttrDecimalPrecisionHelper.setPrecisionStr(productNum.toString(), stockAccuracy));
            }
            if (costVisible) {
                outInObject.put(FlowSubFormEnum.COST.getAttr(), productCost);
                if (isAmount) {
                    outInObject.put(FlowSubFormEnum.COST_TOTAL.getAttr(), AttrDecimalPrecisionHelper.parseThousandth(Arith.mul(productNum, Arith.round(batchFlowBillEntity.getProductCost(), costAccuracy)), costAccuracy));
                } else {
                    outInObject.put(FlowSubFormEnum.COST_TOTAL.getAttr(), attrDecimalPrecisionHelper.setPrecision(Arith.mul(productNum, Arith.round(batchFlowBillEntity.getProductCost(),costAccuracy)), costAccuracy));
                }
            } else {
                outInObject.put(FlowSubFormEnum.COST.getAttr(), invisibleStyle);
                outInObject.put(FlowSubFormEnum.COST_TOTAL.getAttr(), invisibleStyle);
            }
            outInArray.add(outInObject);
            data.put(BatchFlowBillEnum.OUT_IN_RECORD.getAttr(), outInArray);
            // 结存数据封装
            JSONArray remainArray = new JSONArray();
            JSONObject remainObject = new JSONObject();
            remainObject.put(FlowSubFormEnum.QUANTITY.getAttr(), remainingStock);
            if (costVisible) {
                remainObject.put(FlowSubFormEnum.COST_TOTAL.getAttr(), remainingCost);
                if (!Objects.equals(remainingStock, 0D)) {
                    if (isAmount) {
                        remainObject.put(FlowSubFormEnum.COST.getAttr(), AttrDecimalPrecisionHelper.parseThousandth(Arith.div(Arith.round(batchFlowBillEntity.getRemainingCost(), costAccuracy), remainingStock), costAccuracy));
                    } else {
                        remainObject.put(FlowSubFormEnum.COST.getAttr(), attrDecimalPrecisionHelper.setPrecision(Arith.div(Arith.round(batchFlowBillEntity.getRemainingCost(), costAccuracy), remainingStock), costAccuracy));
                    }
                } else {
                    // 移动端需要占位, 给个空字符串。
                    if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                        remainObject.put(FlowSubFormEnum.COST.getAttr(), "");
                    }
                }
            } else {
                remainObject.put(FlowSubFormEnum.COST.getAttr(), invisibleStyle);
                remainObject.put(FlowSubFormEnum.COST_TOTAL.getAttr(), invisibleStyle);
            }
            remainArray.add(remainObject);
            data.put(BatchFlowBillEnum.REMAINING_STOCK.getAttr(), remainArray);
            paasFormDataEntityExt.setData(data);
            paasFormDataESList.add(paasFormDataEntityExt);
        }
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        return paasFormDataEsListVO;
    }


    @Override
    public PaasFormDataEsListVO marketActivityList(FormDataListDTO formDataListDTO) throws XbbException {

        return commonListQry.execute(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO marketingActivity(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions();
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();

        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
        if (Objects.isNull(paasFormExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        // 解释处理
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);

        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(businessType, corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(),null);
        paasFormDataEsListVO.setForm(paasFormEntityExt);
        paasFormDataEsListVO.setHeadList(explainList);
        paasFormDataEsListVO.setBusinessType(formDataListDTO.getBusinessType());
        formDataListSearchHelp.setButtons(formDataListDTO, paasFormDataEsListVO);
        // 查看权限，没有则返回空列表
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!permSet.contains(ProPermissionAliasEnum.MARKETING_ACTIVITY_VIEW.getAlias())) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        // 查询条件
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("start", (long)(page - 1) * pageSize);
        params.put("pageSize", pageSize);
        // 基础信息封装
        if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            for (ConditionsEntityExt conditionsEntityExt : conditionList) {
              if (Objects.equals(conditionsEntityExt.getAttr(), MarketingActivityManagementEnum.CREATOR_ID.getAttr())) {
                  if (Objects.equals(ConditionEnum.EQUAL.getSymbol(), conditionsEntityExt.getSymbol())) {
                      if (Objects.equals(conditionsEntityExt.getValue().get(0), -1)) {
                          conditionsEntityExt.setValue(Arrays.asList(formDataListDTO.getUserId()));
                      }else if (Objects.equals(conditionsEntityExt.getValue().get(0), -2)){
                          List subIdListByDataPermission = userModel.getSubIdListByDataPermission(DataPermissionEnum.DEPARTMENT.getCode(), formDataListDTO.getUserId(), corpid, BasicConstant.ONE, true);
                          conditionsEntityExt.setValue(subIdListByDataPermission);
                          conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                      }
                  }
              }
            }
        }

        // 条件筛选
        for (ConditionsEntityExt conditionsEntityExt : conditionList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), MarketingActivityManagementEnum.STATUS.getAttr())) {
                params.put("status", Integer.valueOf(conditionsEntityExt.getValue().get(0).toString()));
            } else if (Objects.equals(conditionsEntityExt.getAttr(), MarketingActivityManagementEnum.CREATOR_ID.getAttr())) {
                if (Objects.equals(ConditionEnum.EQUAL.getSymbol(), conditionsEntityExt.getSymbol())) {
                    params.put("creatorId", conditionsEntityExt.getValue().get(0));
                }else if (Objects.equals(ConditionEnum.NOEQUAL.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("creatorIdNoEqual", conditionsEntityExt.getValue().get(0));
                }else if (Objects.equals(ConditionEnum.IN.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("creatorIdInclude",  conditionsEntityExt.getValue());
                }else if (Objects.equals(ConditionEnum.NOIN.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("creatorIdNoIn",  conditionsEntityExt.getValue());
                }else if (Objects.equals(ConditionEnum.EMPTY.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("creatorIdEmpty", "");
                }
            }else if (Objects.equals(conditionsEntityExt.getAttr(), "dataId")) {
                params.put("idIn", conditionsEntityExt.getValue());
            }
        }

        String nameLike = formDataListDTO.getNameLike();
        if (StringUtil.isNotEmpty(nameLike)) {
            params.put("nameLike", nameLike);
        }
        // 日期筛选
        FiscalYearTimePojo fiscalYearTimePojo = formDataListDTO.getTimeFilter() == null ? new FiscalYearTimePojo() : formDataListDTO.getTimeFilter();
        int startMonth = 1;
        fiscalYearTimePojo.setStartMonth(startMonth);
        Integer timeType = fiscalYearTimePojo.getTimeType() == null ? fiscalYearTimePojo.getTimeType4DefaultYear() : fiscalYearTimePojo.getTimeType();

        TimeTypeEnum timeTypeEnum = TimeTypeEnum.getByCode(timeType);
        if (timeTypeEnum == null) {
            timeType = TimeTypeEnum.DAY.getCode();
        }
        fiscalYearTimePojo.setTimeTypeEnum(timeTypeEnum);
        Integer searchStartTime = FiscalYearHelp.getStartTime(fiscalYearTimePojo, timeType, startMonth);
        Integer searchEndTime = FiscalYearHelp.getEndTime(fiscalYearTimePojo, searchStartTime, timeType, startMonth);
        params.put("greaterEqualThanDate", searchEndTime);
        params.put("lessThanDate", searchStartTime);

        params.put("orderByStr", "add_time desc");

        List<CouponTempleteEntity> couponTempleteEntities = couponTempleteModel.findEntities(params);
        paasFormDataEsListVO.setBottomPermissions(new ArrayList<>());
        if (couponTempleteEntities.size() == 0) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        Integer count = couponTempleteModel.getEntityCount(params);
        paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(count));

        //经销商级别，地区，名称
        Map<String, String> distributorLevelMap = new HashMap<>();
        Map<Long, String> distributorAreaMap = new HashMap<>();
        Map<Long,String> distributorNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        List<ItemPoJo> distributorLevel = marketingHelp.getDistributorLevel(corpid);
        distributorLevel.forEach(item -> distributorLevelMap.put(item.getValue().toString(), item.getText()));
        List<DistributorAreaEntity> allDistributorArea = distributorAreaModel.findAllDistributorArea(corpid);
        allDistributorArea.forEach(item -> distributorAreaMap.put(item.getId(), item.getName()));
        List<String> creatorIds = new ArrayList<>();
        List<Long> distributorIds = new ArrayList<>();
        List<Long> onlineCoupons = new ArrayList<>();
        List<CouponTempleteEntity> offLineCoupons = new ArrayList<>();
        for (CouponTempleteEntity couponTempleteEntity : couponTempleteEntities) {
            JSONObject couponData = couponTempleteEntity.getData();
            String applicableObjectType = couponData.getString(MarketingActivityManagementEnum.APPLICABLE_OBJECT_TYPE.getAttr());
            if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
                JSONArray distributor = couponData.getJSONArray(MarketingBaseEnum.DISTRIBUTOR.getAttr());
                if (Objects.nonNull(distributor) && !distributor.isEmpty()) {
                    for (int i = 0; i < distributor.size(); i++) {
                        distributorIds.add(distributor.getLong(i));
                    }
                }
            }
            creatorIds.add(couponTempleteEntity.getCreatorId());
            if (Objects.equals(couponTempleteEntity.getStatus(), MarketingStatusEnum.ONLINE.getCode())) {
                if (DateTimeUtil.getTodayInt() > couponTempleteEntity.getEndTime()) {
                    //到期处理自动下架
                    String key = corpid + StringConstant.UNDER_LINE + couponTempleteEntity.getId();
                    String value = Objects.isNull(paasRedisHelper.getValue(RedisPrefixConstant.COUPON_NUM_KEY, key)) ? "0" : paasRedisHelper.getValue(RedisPrefixConstant.COUPON_NUM_KEY, key);
                    couponTempleteEntity.setGetNum(couponTempleteEntity.getCouponNum() - Integer.parseInt(value));
                    paasRedisHelper.removeValue(RedisPrefixConstant.COUPON_NUM_KEY, key);
                    couponTempleteEntity.setStatus(MarketingStatusEnum.OFFLINE.getCode());
                    couponTempleteEntity.getData().put(MarketingBaseEnum.STATUS.getAttr(),MarketingStatusEnum.OFFLINE.getCode());
                    offLineCoupons.add(couponTempleteEntity);
                }else {
                    onlineCoupons.add(couponTempleteEntity.getId());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(offLineCoupons)) {
            Runnable runnable = () -> {
                try {
                    couponTempleteModel.updateStatus(offLineCoupons, corpid);
                } catch (XbbException e) {
                   LOG.error("saasListService.marketingActivity同步下架状态 出错：", e);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
        }
        Map<Long, Integer> couponNumMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(onlineCoupons)) {
            for (Long onlineCoupon : onlineCoupons) {
                String key = corpid + StringConstant.UNDER_LINE + onlineCoupon;
                String value = Objects.isNull(paasRedisHelper.getValue(RedisPrefixConstant.COUPON_NUM_KEY, key)) ? "0" : paasRedisHelper.getValue(RedisPrefixConstant.COUPON_NUM_KEY, key);
                couponNumMap.put(onlineCoupon, Integer.parseInt(value));
            }
        }
        List<CustomerEntityExt> distributorNameList = customerModel.getByKeys(distributorIds, corpid);
        distributorNameList.forEach(item -> distributorNameMap.put(item.getId(), item.getData().getString(DistributorEnum.NAME.getAttr())));
        Map<String, String> userNameMap = userModel.getUserNameMap(corpid, creatorIds);
        // 列表数据封装
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>(couponTempleteEntities.size());
        for (CouponTempleteEntity couponTempleteEntity : couponTempleteEntities) {
            JSONObject couponData = couponTempleteEntity.getData();
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setDataId(couponTempleteEntity.getId());
            JSONObject data = new JSONObject();
            //公共处理
            Long beginTime = couponTempleteEntity.getBeginTime();
            Long endTime = couponTempleteEntity.getEndTime();
            String beginTimeStr = DateTimeUtil.getDateStringEpochSecond(beginTime);
            String endTimeStr = DateTimeUtil.getDateStringEpochSecond(endTime);
            data.put(MarketingActivityManagementEnum.NAME.getAttr(), couponTempleteEntity.getName());
            data.put(MarketingActivityManagementEnum.TYPE.getAttr(), XbbRefTypeEnum.getByCode(couponTempleteEntity.getBusinessType()).getName());
            data.put(MarketingActivityManagementEnum.ACTIVITY_TIME.getAttr(), String.format(StringConstant.TIME_RANGE, beginTimeStr, endTimeStr));

            String applicableObjectType = couponData.getString(MarketingActivityManagementEnum.APPLICABLE_OBJECT_TYPE.getAttr());
            data.put(MarketingActivityManagementEnum.APPLICABLE_OBJECT_TYPE.getAttr(), ApplicableObjectTypeEnum.getByCode(applicableObjectType));
            //解析适用地区
            StringBuilder area = new StringBuilder();
            JSONArray distributorArea = couponData.getJSONArray(MarketingActivityManagementEnum.APPLICABLE_LOCATION.getAttr());
            if (Objects.nonNull(distributorArea) && !distributorArea.isEmpty()) {
                for (int i = 0; i < distributorArea.size(); i++) {
                    if (Objects.nonNull(distributorAreaMap.get(distributorArea.getLong(i)))) {
                        area.append(distributorAreaMap.get(distributorArea.getLong(i))).append(StringConstant.COMMA);
                    }
                }
                if (area.length() > 1) {
                    area.deleteCharAt(area.length() - 1);
                }
            }else {
                area.append(ApplicableObjectTypeEnum.ALL.getName());
            }
            data.put(MarketingActivityManagementEnum.APPLICABLE_LOCATION.getAttr(), area.toString());
            //解析适用人群
            StringBuilder objectName = new StringBuilder();
            if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.ALL.getCode())) {
                objectName = objectName.append(ApplicableObjectTypeEnum.ALL.getName());
            }else if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.DISTRIBUTOR_LEVEL.getCode())) {
                JSONArray distributor = couponData.getJSONArray(MarketingBaseEnum.DISTRIBUTOR_LEVEL.getAttr());
                if (Objects.nonNull(distributor) && !distributor.isEmpty()) {
                    for (int i = 0; i < distributor.size(); i++) {
                        if (Objects.nonNull(distributorLevelMap.get(distributor.getString(i)))) {
                            objectName.append(distributorLevelMap.get(distributor.getString(i))).append(StringConstant.COMMA);
                        }
                    }
                    if (objectName.length() > 1) {
                        objectName.deleteCharAt(objectName.length() - 1);
                    }
                }
            }else if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
                JSONArray distributor = couponData.getJSONArray(MarketingBaseEnum.DISTRIBUTOR.getAttr());
                if (Objects.nonNull(distributor) && !distributor.isEmpty()) {
                    for (int i = 0; i < distributor.size(); i++) {
                        if (Objects.nonNull(distributorNameMap.get(distributor.getLong(i)))) {
                            objectName.append(distributorNameMap.get(distributor.getLong(i))).append(StringConstant.COMMA);
                        }
                    }
                    if (objectName.length() > 1) {
                        objectName.deleteCharAt(objectName.length() - 1);
                    }
                }
            }
            data.put(MarketingActivityManagementEnum.APPLICABLE_OBJECT.getAttr(), objectName.toString());
            data.put(MarketingActivityManagementEnum.NUM.getAttr(), StringConstant.UNDER_LINE);
            if (couponTempleteEntity.getCouponNum() >= 0) {
                data.put(MarketingActivityManagementEnum.NUM.getAttr(), couponTempleteEntity.getCouponNum());
            }
            if (Objects.equals(couponTempleteEntity.getStatus(), MarketingStatusEnum.ONLINE.getCode())) {
                data.put(MarketingActivityManagementEnum.GET_NUM.getAttr(), couponTempleteEntity.getCouponNum() - couponNumMap.getOrDefault(couponTempleteEntity.getId(), 0));
            }else {
                data.put(MarketingActivityManagementEnum.GET_NUM.getAttr(), couponTempleteEntity.getGetNum());
            }
            data.put(MarketingActivityManagementEnum.USED_NUM.getAttr(), couponTempleteEntity.getUsedNum());
            data.put(MarketingActivityManagementEnum.WRITE_OFF_RATE.getAttr(), StringConstant.UNDER_LINE);
            if (data.getIntValue(MarketingActivityManagementEnum.GET_NUM.getAttr()) != 0) {
                String percentFormat2 = commonHelp.getPercentFormat2(Arith.div(couponTempleteEntity.getUsedNum(), data.getIntValue(MarketingActivityManagementEnum.GET_NUM.getAttr())),2);
                data.put(MarketingActivityManagementEnum.WRITE_OFF_RATE.getAttr(), percentFormat2);
            }
            paasFormDataEntityExt.setActivityStatus(couponTempleteEntity.getStatus());
            data.put(MarketingActivityManagementEnum.STATUS.getAttr(), MarketingStatusEnum.getByCode(couponTempleteEntity.getStatus()));
            data.put(MarketingActivityManagementEnum.CREATOR_ID.getAttr(), userNameMap.getOrDefault(couponTempleteEntity.getCreatorId(), ""));
            data.put(MarketingActivityManagementEnum.ADD_TIME.getAttr(), couponTempleteEntity.getAddTime());
            paasFormDataEntityExt.setData(data);
            paasFormDataEntityExt.setCreatorId(couponTempleteEntity.getCreatorId());
            paasFormDataEntityExt.setAddTime(couponTempleteEntity.getAddTime());
            paasFormDataESList.add(paasFormDataEntityExt);
        }
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        // 设置操作方式
        AbstractOptionHandle abstractOptionHandle = optionFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        abstractOptionHandle.setOptionsInExplain(formDataListDTO, explainList, paasFormDataEsListVO);
        abstractOptionHandle.setOptionsInData(formDataListDTO, paasFormDataEsListVO);
        // 列表排序
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO productPriceList(FormDataListDTO formDataListDTO) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        // 生成表头
        List<String> fieldAttr = Arrays.asList(PriceSetEnum.NAME.getAttr(), PriceSetEnum.PRIORITY.getAttr(), PriceProductEnum.NAME.getAttr());
        List<FieldAttrEntity> fieldList = productHelp.getProductPriceFieldList(corpid);
        fieldList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), PriceSetEnum.PRODUCT.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), PriceSetEnum.ADAPTER_TYPE.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), PriceProductEnum.PARENT_ID.getAttr()));
        fieldList.forEach(fieldAttrEntity -> {
            fieldAttrEntity.setEditable(0);
            if (fieldAttr.contains(fieldAttrEntity.getAttr())) {
                fieldAttrEntity.setFixed(true);
            }
        });
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(formDataListDTO.getBusinessType(), formDataListDTO.getCorpid(), DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        if (paasFormEntityExt == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        // 筛选项
        List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
        conditions = conditions != null ? conditions : new ArrayList<>();
        ConditionsEntityExt productCondition = null;
        CustomerEntityExt customerEntityExt = null;
        List<ConditionEntity> priceConditions = new ArrayList<>();
        for (ConditionsEntityExt condition : conditions) {
            ConditionEntity conditionEntity = new ConditionEntity();
            conditionEntity.setAttr(condition.getAttr());
            conditionEntity.setSymbol(condition.getSymbol());
            if (Objects.equals(condition.getAttr(), PriceSetEnum.PRODUCT.getAttr())) {
                productCondition = condition;
            } else if (Objects.equals(condition.getAttr(), PriceSetEnum.NAME.getAttr())) {
                if (ConditionEnum.IN.getSymbol().equals(condition.getSymbol()) || ConditionEnum.NOIN.getSymbol().equals(condition.getSymbol())) {
                    conditionEntity.setValues(condition.getValue());
                } else {
                    conditionEntity.setValue(CollectionsUtil.isNotEmpty(condition.getValue()) ? condition.getValue().get(0) : "");
                }
                priceConditions.add(conditionEntity);
            } else if (Objects.equals(condition.getAttr(), PriceSetEnum.ADAPTER_TYPE.getAttr())) {
                if (CollectionsUtil.isNotEmpty(condition.getValue())) {
                    if (ConditionEnum.IN.getSymbol().equals(condition.getSymbol()) || ConditionEnum.NOIN.getSymbol().equals(condition.getSymbol())) {
                        List<Long> customerIds = new ArrayList<>();
                        condition.getValue().forEach(o -> customerIds.add(Long.parseLong(o.toString())));
                        List<CustomerEntityExt> customerList = customerModel.getByKeys(customerIds, corpid);
                        List<Object> formIds = new ArrayList<>();
                        customerList.forEach(customer -> formIds.add(customer.getFormId()));
                        conditionEntity.setValues(formIds);
                    } else {
                        customerEntityExt = customerModel.getByKey(Long.parseLong(condition.getValue().get(0).toString()), corpid);
                        if (Objects.isNull(customerEntityExt)) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nMessageUtil.getMessage(MessageConstant.FORM_DATA_NOT_EXIST));
                        }
                        conditionEntity.setValue(customerEntityExt.getFormId());
                    }
                    priceConditions.add(conditionEntity);
                }
            }
        }
        // 价目表
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.ENABLE, BasicConstant.ONE);
        List<PriceSetEntity> priceSetList = priceSetModel.getPricesByConditions(param, priceConditions);
        Long now = DateTimeUtil.getInt();
        //过滤掉不符合时间的价目表
        priceSetList.removeIf(PriceSetEntity -> (Objects.nonNull(PriceSetEntity.getStartTime()) && now < PriceSetEntity.getStartTime()) || (Objects.nonNull(PriceSetEntity.getEndTime()) && now > PriceSetEntity.getEndTime()));
        Map<Long, PriceSetEntity> priceMap = new HashMap<>();
        List<Long> priceIdList = new ArrayList<>();
        if (customerEntityExt != null) {
            JSONObject data = customerEntityExt.getData();
            List<String> addressAttrList = Arrays.asList("province", "city", "district", "address");
            Outer:
            for (PriceSetEntity priceSetEntity : priceSetList) {
                if (Objects.equals(priceSetEntity.getAdapterType(), BasicConstant.ZERO)) {
                    priceIdList.add(priceSetEntity.getId());
                    priceMap.put(priceSetEntity.getId(), priceSetEntity);
                    continue;
                }
                List<ConditionsEntityExt> conditionsEntityExts = priceSetEntity.getRule().toJavaList(ConditionsEntityExt.class);
                for (ConditionsEntityExt conditionsEntityExt : conditionsEntityExts) {
                    String attr = conditionsEntityExt.getAttr();
                    List<Object> value = conditionsEntityExt.getValue();
                    //过滤地址不符合的价目表
                    if (addressAttrList.contains(conditionsEntityExt.getAttr())) {
                        if (Objects.isNull(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr())) || Objects.isNull(value) || value.isEmpty()
                                || !Objects.equals(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()).getString(conditionsEntityExt.getAttr()), value.get(0).toString())) {
                            continue Outer;
                        }
                    } else if (Objects.equals(conditionsEntityExt.getFieldType(), FieldTypeEnum.SERIALNO.getType())) {
                        data.put(FieldTypeEnum.SERIALNO.getAlias(), customerEntityExt.getSerialNo());
                        if (!webCommonDataValueMatchHandle.match(conditionsEntityExt, data)) {
                            continue Outer;
                        }
                    } else {
                        Object dataValue = data.get(attr);
                        if (dataValue instanceof List) {
                            if (!webListDataValueMatchHandle.match(conditionsEntityExt, data)) {
                                continue Outer;
                            }
                        } else {
                            if (!webCommonDataValueMatchHandle.match(conditionsEntityExt, data)) {
                                continue Outer;
                            }
                        }
                    }
                }
                priceIdList.add(priceSetEntity.getId());
                priceMap.put(priceSetEntity.getId(), priceSetEntity);
            }
        } else {
            priceSetList.forEach(priceSetEntity -> {
                        priceMap.put(priceSetEntity.getId(), priceSetEntity);
                        priceIdList.add(priceSetEntity.getId());
                    }
            );
        }

        // 价目产品
        param.clear();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL);
        param.put(ParameterConstant.PRODUCT_ID_IN, productCondition != null ? productCondition.getValue() : null);
        param.put(ParameterConstant.ORDER_BY_STR, "product_id asc");
        param.put("priceIdIn", priceIdList);
        PageHelper pageHelper = PageHelperUtil.getPageHelper(param, priceProductSetModel, formDataListDTO.getPage(), formDataListDTO.getPageSize());
        List<PriceProductSetEntity> priceProductSetList = (List<PriceProductSetEntity>) PageHelperUtil.getEntityList(param, pageHelper, priceProductSetModel);
        // 产品信息
        Set<Long> productIdSet = new HashSet<>();
        priceProductSetList.forEach(priceProductSetEntity -> productIdSet.add(priceProductSetEntity.getProductId()));
        List<PaasFormDataEntityExt> productEntityList = productService.getProductListById(productIdSet, corpid, DelEnum.NORMAL);
        productService.formatChildSpecification(productEntityList, corpid);
        Map<Long, JSONObject> productMap = new HashMap<>(productEntityList.size());
        productEntityList.forEach(item -> productMap.put(item.getDataId(), item.getData()));

        List<ItemPoJo> businessUnitItems = relativeProductHelp.getBusinessUnitItems(corpid);
        List<PaasFormDataEntityExt> paasFormDataESList = new ArrayList<>(priceSetList.size());
        for (PriceProductSetEntity priceProductSetEntity : priceProductSetList) {
            // 价目名称
            PriceSetEntity priceSetEntity = priceMap.get(priceProductSetEntity.getPriceId());
            // 产品
            JSONObject productData = productMap.get(priceProductSetEntity.getProductId());
            if (Objects.isNull(productData)) {
                // 产品呗删除，不展示价目表信息
                continue;
            }

            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setDataId(priceProductSetEntity.getId());
            JSONObject data = new JSONObject();
            data.put(PriceSetEnum.NAME.getAttr(), priceSetEntity.getName());
            data.put(PriceSetEnum.PRIORITY.getAttr(), priceSetEntity.getPriority());
            data.put(PriceProductEnum.NAME.getAttr(), productData.getString(ProductEnum.NAME.getAttr()));
            data.put(PriceProductEnum.PRODUCT_NO.getAttr(), productData.getString(ProductEnum.PRODUCT_NO.getAttr()));
            data.put(PriceProductEnum.SPECIFICATION.getAttr(), productData.getString(ProductEnum.SPECIFICATION.getAttr()));
            data.put(PriceProductEnum.PRODUCT_IMGS.getAttr(), productData.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()));
            for (ItemPoJo itemPoJo : businessUnitItems) {
                if (Objects.equals(itemPoJo.getValue().toString(), priceProductSetEntity.getProductUnit())) {
                    data.put(PriceProductEnum.UNIT.getAttr(), itemPoJo.getText());
                    break;
                }
            }
            data.put(PriceProductEnum.DISCOUNT.getAttr(), priceProductSetEntity.getDiscount());
            data.put(PriceProductEnum.PRICE.getAttr(), priceProductSetEntity.getProductPrice());
            data.put(PriceProductEnum.SELLING_PRICE.getAttr(), priceProductSetEntity.getSellingPrice());
            data.put(PriceProductEnum.SELLING_PRICE_UP.getAttr(), priceProductSetEntity.getPriceCap());
            data.put(PriceProductEnum.SELLING_PRICE_DOWN.getAttr(), priceProductSetEntity.getPriceFloor());

            paasFormDataEntityExt.setData(data);
            paasFormDataESList.add(paasFormDataEntityExt);
        }
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        paasFormDataEsListVO.setHeadList(fieldList);
        paasFormDataEsListVO.setForm(paasFormEntityExt);
        paasFormDataEsListVO.setExplainMap(ExplainUtil.getExplainMap(JSON.toJSONString(fieldList)));
        // 头部按钮
        if (formDataListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PRICE_PRODUCT_EXPORT.getAlias())) {
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(ListTopButtonEnum.PRODUCT_PRICE.getAnEnum(), buttonPojo);
            List<SaasSubButtonEnum> saasSubButtonEnumList = SaasSubButtonEnum.getByPermissionAlias(ListTopButtonEnum.PRODUCT_PRICE.getBusinessType(),ListTopButtonEnum.PRODUCT_PRICE,formDataListDTO.getLoginUser().getPermSet());
            List<ButtonPojo> subButtonList = new ArrayList<ButtonPojo>(){{
                add(new ButtonPojo(){{BeanUtil.copyProperties(ListTopButtonEnum.PRODUCT_PRICE.getAnEnum(), this);}});
            }};
            saasSubButtonEnumList.forEach(item->{
                subButtonList.add(new ButtonPojo(){{setAttr(item.getAlias());setValue(item.getName());}});
            });
            buttonPojo.setSubButtons(subButtonList);
            paasFormDataEsListVO.setTopPermissions(Collections.singletonList(buttonPojo));
        } else {
            paasFormDataEsListVO.setTopPermissions(new ArrayList<>());
        }
        paasFormDataEsListVO.setBottomPermissions(new ArrayList<>());
        paasFormDataEsListVO.setBusinessType(XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode());
        paasFormDataEsListVO.setPageHelper(pageHelper);
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO promotionActivity(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions();
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();

        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
        if (Objects.isNull(paasFormExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        // 解释处理
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);

        for (FieldAttrEntity fieldAttrEntity : explainList) {
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SELECT_PRODUCT.getType())) {
                List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                for (FieldAttrEntity item : items) {
                    if (Objects.equals(item.getAttr(), SelectProductEnum.PRODUCT.getAttr())) {
                        item.setFieldType(FieldTypeEnum.TEXT.getType());
                        break;
                    }
                }
                break;
            }
        }

        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(businessType, corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(),null);
        paasFormDataEsListVO.setForm(paasFormEntityExt);
        paasFormDataEsListVO.setHeadList(explainList);
        paasFormDataEsListVO.setBusinessType(formDataListDTO.getBusinessType());
        formDataListSearchHelp.setButtons(formDataListDTO, paasFormDataEsListVO);
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        // 查看权限，没有则返回空列表
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!permSet.contains(ProPermissionAliasEnum.PROMOTION_ACTIVITY_VIEW.getAlias())) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        // 查询条件
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("start", (long)(page - 1) * pageSize);
        params.put("pageSize", pageSize);

        // 基础信息封装
        if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            for (ConditionsEntityExt conditionsEntityExt : conditionList) {
                if (Objects.equals(conditionsEntityExt.getAttr(), MarketingActivityManagementEnum.CREATOR_ID.getAttr())) {
                    if (Objects.equals(ConditionEnum.EQUAL.getSymbol(), conditionsEntityExt.getSymbol())) {
                        if (Objects.equals(conditionsEntityExt.getValue().get(0), -1)) {
                            conditionsEntityExt.setValue(Arrays.asList(formDataListDTO.getUserId()));
                        }else if (Objects.equals(conditionsEntityExt.getValue().get(0), -2)){
                            List subIdListByDataPermission = userModel.getSubIdListByDataPermission(DataPermissionEnum.DEPARTMENT.getCode(), formDataListDTO.getUserId(), corpid, BasicConstant.ONE, true);
                            conditionsEntityExt.setValue(subIdListByDataPermission);
                            conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                        }
                    }
                }
            }
        }
        // 条件筛选
        for (ConditionsEntityExt conditionsEntityExt : conditionList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), MarketingActivityManagementEnum.STATUS.getAttr())) {
                params.put("status", Integer.valueOf(conditionsEntityExt.getValue().get(0).toString()));
            } else if (Objects.equals(conditionsEntityExt.getAttr(), MarketingActivityManagementEnum.CREATOR_ID.getAttr())) {
                if (Objects.equals(ConditionEnum.EQUAL.getSymbol(), conditionsEntityExt.getSymbol())) {
                    params.put("creatorId", conditionsEntityExt.getValue().get(0));
                }else if (Objects.equals(ConditionEnum.NOEQUAL.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("creatorIdNoEqual", conditionsEntityExt.getValue().get(0));
                }else if (Objects.equals(ConditionEnum.IN.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("creatorIdInclude",  conditionsEntityExt.getValue());
                }else if (Objects.equals(ConditionEnum.NOIN.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("creatorIdNoIn",  conditionsEntityExt.getValue());
                }else if (Objects.equals(ConditionEnum.EMPTY.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("creatorIdEmpty", "");
                }
            }else if (Objects.equals(conditionsEntityExt.getAttr(), "dataId")) {
                params.put("idIn", conditionsEntityExt.getValue());
            }
        }

        String nameLike = formDataListDTO.getNameLike();
        if (StringUtil.isNotEmpty(nameLike)) {
            params.put("nameLike", nameLike);
        }
        // 日期筛选
        FiscalYearTimePojo fiscalYearTimePojo = formDataListDTO.getTimeFilter() == null ? new FiscalYearTimePojo() : formDataListDTO.getTimeFilter();
        int startMonth = 1;
        fiscalYearTimePojo.setStartMonth(startMonth);
        Integer timeType = fiscalYearTimePojo.getTimeType() == null ? fiscalYearTimePojo.getTimeType4DefaultYear() : fiscalYearTimePojo.getTimeType();
        TimeTypeEnum timeTypeEnum = TimeTypeEnum.getByCode(timeType);
        if (timeTypeEnum == null) {
            timeType = TimeTypeEnum.DAY.getCode();
        }
        fiscalYearTimePojo.setTimeTypeEnum(timeTypeEnum);
        Integer searchStartTime = FiscalYearHelp.getStartTime(fiscalYearTimePojo, timeType, startMonth);
        Integer searchEndTime = FiscalYearHelp.getEndTime(fiscalYearTimePojo, searchStartTime, timeType, startMonth);
        params.put("greaterEqualThanDate", searchEndTime);
        params.put("lessThanDate", searchStartTime);

        params.put("orderByStr", "add_time desc");


        List<PromotionActivityEntity> entities = promotionActivityModel.findEntities(params);
        paasFormDataEsListVO.setBottomPermissions(new ArrayList<>());
        if (entities.size() == 0) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        Integer count = promotionActivityModel.getEntityCount(params);
        paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(count));

        //经销商级别，地区，名称
        Map<String, String> distributorLevelMap = new HashMap<>();
        Map<Long, String> distributorAreaMap = new HashMap<>();
        Map<Long,String> distributorNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        List<ItemPoJo> distributorLevel = marketingHelp.getDistributorLevel(corpid);
        distributorLevel.forEach(item -> distributorLevelMap.put(item.getValue().toString(), item.getText()));
        List<DistributorAreaEntity> allDistributorArea = distributorAreaModel.findAllDistributorArea(corpid);
        allDistributorArea.forEach(item -> distributorAreaMap.put(item.getId(), item.getName()));
        List<String> creatorIds = new ArrayList<>();
        List<Long> distributorIds = new ArrayList<>();
        List<Long> promotionActivityIds = new ArrayList<>();
        List<PromotionActivityEntity> offLineActivity = new ArrayList<>();
        for (PromotionActivityEntity promotionActivityEntity : entities) {
            JSONObject data = promotionActivityEntity.getData();
            String applicableObjectType = data.getString(MarketingActivityManagementEnum.APPLICABLE_OBJECT_TYPE.getAttr());
            if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
                JSONArray distributor = data.getJSONArray(MarketingBaseEnum.DISTRIBUTOR.getAttr());
                if (Objects.nonNull(distributor) && !distributor.isEmpty()) {
                    for (int i = 0; i < distributor.size(); i++) {
                        distributorIds.add(distributor.getLong(i));
                    }
                }
            }
            creatorIds.add(promotionActivityEntity.getCreatorId());
            promotionActivityIds.add(promotionActivityEntity.getId());
            if (Objects.equals(promotionActivityEntity.getStatus(), MarketingStatusEnum.ONLINE.getCode())) {
                if (DateTimeUtil.getTodayInt() > promotionActivityEntity.getEndTime()) {
                    //到期处理自动下架
                    promotionActivityEntity.setStatus(MarketingStatusEnum.OFFLINE.getCode());
                    promotionActivityEntity.getData().put(MarketingBaseEnum.STATUS.getAttr(), MarketingStatusEnum.OFFLINE.getCode());
                    offLineActivity.add(promotionActivityEntity);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(offLineActivity)) {
            Runnable runnable = () -> {
                try {
                    promotionActivityModel.updateStatus(offLineActivity, corpid);
                } catch (XbbException e) {
                    LOG.error("saasListService.promotionActivity同步下架状态 出错：", e);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
        }

        Map<Long, List<PromotionProductEntity>> promotionProductMap = new HashMap<>();
        List<Long> productList = new ArrayList<>();
        if (!promotionActivityIds.isEmpty()) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("refIdIn", promotionActivityIds);
            param.put("del", 0);
            List<PromotionProductEntity> promotionProductEntityList = promotionProductModel.findEntities(param);
            for (PromotionProductEntity entity : promotionProductEntityList) {
                List<PromotionProductEntity> productEntities = promotionProductMap.getOrDefault(entity.getRefId(), new ArrayList<>());
                productEntities.add(entity);
                promotionProductMap.put(entity.getRefId(), productEntities);
                productList.add(entity.getProductId());
            }
        }

        Map<Long, PaasFormDataEntityExt> productMap = marketingHelp.marketingProductSaveMap(corpid,productList);
        List<CustomerEntityExt> distributorNameList = customerModel.getByKeys(distributorIds, corpid);
        distributorNameList.forEach(item -> distributorNameMap.put(item.getId(), item.getData().getString(DistributorEnum.NAME.getAttr())));
        Map<String, String> userNameMap = userModel.getUserNameMap(corpid, creatorIds);
        // 列表数据封装
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>(entities.size());
        for (PromotionActivityEntity promotionActivityEntity : entities) {
            JSONObject promotionData = promotionActivityEntity.getData();
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setDataId(promotionActivityEntity.getId());
            JSONObject data = new JSONObject();
            //公共处理
            Long beginTime = promotionActivityEntity.getBeginTime();
            Long endTime = promotionActivityEntity.getEndTime();
            String beginTimeStr = DateTimeUtil.getDateStringEpochSecond(beginTime);
            String endTimeStr = DateTimeUtil.getDateStringEpochSecond(endTime);
            data.put(PromotionActivityManagementEnum.NAME.getAttr(), promotionActivityEntity.getName());
            data.put(PromotionActivityManagementEnum.TYPE.getAttr(), XbbRefTypeEnum.getByCode(promotionActivityEntity.getBusinessType()).getName());
            data.put(PromotionActivityManagementEnum.ACTIVITY_TIME.getAttr(), String.format(StringConstant.TIME_RANGE, beginTimeStr, endTimeStr));

            String applicableObjectType = promotionData.getString(PromotionActivityManagementEnum.APPLICABLE_OBJECT_TYPE.getAttr());
            data.put(MarketingActivityManagementEnum.APPLICABLE_OBJECT_TYPE.getAttr(), ApplicableObjectTypeEnum.getByCode(applicableObjectType));
            //解析适用地区
            StringBuilder area = new StringBuilder();
            JSONArray distributorArea = promotionData.getJSONArray(PromotionActivityManagementEnum.APPLICABLE_LOCATION.getAttr());
            if (Objects.nonNull(distributorArea) && !distributorArea.isEmpty()) {
                for (int i = 0; i < distributorArea.size(); i++) {
                    if (Objects.nonNull(distributorAreaMap.get(distributorArea.getLong(i)))) {
                        area.append(distributorAreaMap.get(distributorArea.getLong(i))).append(StringConstant.COMMA);
                    }
                }
                if (area.length() > 1) {
                    area.deleteCharAt(area.length() - 1);
                }
            }else {
                area.append(ApplicableObjectTypeEnum.ALL.getName());
            }
            data.put(PromotionActivityManagementEnum.APPLICABLE_LOCATION.getAttr(), area.toString());
            //解析适用人群
            StringBuilder objectName = new StringBuilder();
            if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.ALL.getCode())) {
                objectName = objectName.append(ApplicableObjectTypeEnum.ALL.getName());
            }else if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.DISTRIBUTOR_LEVEL.getCode())) {
                JSONArray distributor = promotionData.getJSONArray(MarketingBaseEnum.DISTRIBUTOR_LEVEL.getAttr());
                if (Objects.nonNull(distributor) && !distributor.isEmpty()) {
                    for (int i = 0; i < distributor.size(); i++) {
                        if (Objects.nonNull(distributorLevelMap.get(distributor.getString(i)))) {
                            objectName.append(distributorLevelMap.get(distributor.getString(i))).append(StringConstant.COMMA);
                        }
                    }
                    if (objectName.length() > 1) {
                        objectName.deleteCharAt(objectName.length() - 1);
                    }
                }
            }else if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
                JSONArray distributor = promotionData.getJSONArray(MarketingBaseEnum.DISTRIBUTOR.getAttr());
                if (Objects.nonNull(distributor) && !distributor.isEmpty()) {
                    for (int i = 0; i < distributor.size(); i++) {
                        if (Objects.nonNull(distributorNameMap.get(distributor.getLong(i)))) {
                            objectName.append(distributorNameMap.get(distributor.getLong(i))).append(StringConstant.COMMA);
                        }
                    }
                    if (objectName.length() > 1) {
                        objectName.deleteCharAt(objectName.length() - 1);
                    }
                }
            }
            data.put(PromotionActivityManagementEnum.APPLICABLE_OBJECT.getAttr(), objectName.toString());
            paasFormDataEntityExt.setActivityStatus(promotionActivityEntity.getStatus());
            data.put(PromotionActivityManagementEnum.STATUS.getAttr(), MarketingStatusEnum.getByCode(promotionActivityEntity.getStatus()));
            data.put(PromotionActivityManagementEnum.PRIORITY.getAttr(), promotionActivityEntity.getPriority());
            data.put(PromotionActivityManagementEnum.CREATOR_ID.getAttr(), userNameMap.getOrDefault(promotionActivityEntity.getCreatorId(), ""));
            data.put(PromotionActivityManagementEnum.ADD_TIME.getAttr(), promotionActivityEntity.getAddTime());

            JSONArray productArray = new JSONArray();
            List<PromotionProductEntity> promotionProductEntities = promotionProductMap.getOrDefault(promotionActivityEntity.getId(), new ArrayList<>());
            for (PromotionProductEntity promotionProductEntity : promotionProductEntities) {
                JSONObject productData = new JSONObject();
                if (productMap.containsKey(promotionProductEntity.getProductId())) {
                    PaasFormDataEntityExt originProduct = productMap.get(promotionProductEntity.getProductId());
                    productData.put("dataId", promotionProductEntity.getProductId());
                    productData.put(PromotionActivityManagementProductEnum.PRODUCT.getAttr(), originProduct.getData().getString(ProductEnum.NAME.getAttr()));
                    productData.put(PromotionActivityManagementProductEnum.SPECIFICATION.getAttr(), originProduct.getData().getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                    productData.put(PromotionActivityManagementProductEnum.DISCOUNT.getAttr(), promotionProductEntity.getDiscount());
                    productArray.add(productData);
                }
            }
            data.put(PromotionActivityManagementEnum.APPLICABLE_PRODUCT.getAttr(), productArray);
            paasFormDataEntityExt.setData(data);
            paasFormDataEntityExt.setCreatorId(promotionActivityEntity.getCreatorId());
            paasFormDataEntityExt.setAddTime(promotionActivityEntity.getAddTime());
            paasFormDataESList.add(paasFormDataEntityExt);
        }
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        // 设置操作方式
        AbstractOptionHandle abstractOptionHandle = optionFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        abstractOptionHandle.setOptionsInExplain(formDataListDTO, explainList, paasFormDataEsListVO);
        abstractOptionHandle.setOptionsInData(formDataListDTO, paasFormDataEsListVO);
        // 列表排序
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO writeOffRecord(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions();
        String corpid = formDataListDTO.getCorpid();
        Integer businessType = formDataListDTO.getBusinessType();
        Integer page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();

        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
        if (Objects.isNull(paasFormExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        // 解释处理
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);

        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(businessType, corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(),null);
        paasFormDataEsListVO.setForm(paasFormEntityExt);
        paasFormDataEsListVO.setHeadList(explainList);
        paasFormDataEsListVO.setBusinessType(formDataListDTO.getBusinessType());
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        // 查看权限，没有则返回空列表
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!permSet.contains(ProPermissionAliasEnum.MARKETING_ACTIVITY_VIEW_RECORD.getAlias())) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        ButtonPojo buttonPojo = new ButtonPojo();
        BeanUtil.copyProperties(SaasButtonEnum.EXPORT, buttonPojo);
        paasFormDataEsListVO.setTopPermissions(Arrays.asList(buttonPojo));
        // 查询条件
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        params.put("start", (long)(page - 1) * pageSize);
        params.put("pageSize", pageSize);


        // 条件筛选
        for (ConditionsEntityExt conditionsEntityExt : conditionList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), WriteOffRecordEnum.ORDER_STATUS.getAttr())) {
                params.put("orderStatus", conditionsEntityExt.getValue().get(0).toString());
            } else if (Objects.equals(conditionsEntityExt.getAttr(), WriteOffRecordEnum.DISTRIBUTOR_ID.getAttr())) {
                if (Objects.equals(ConditionEnum.EQUAL.getSymbol(), conditionsEntityExt.getSymbol())) {
                    params.put("distributorId", conditionsEntityExt.getValue().get(0));
                }else if (Objects.equals(ConditionEnum.NOEQUAL.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("distributorIdNoEqual", conditionsEntityExt.getValue().get(0));
                }else if (Objects.equals(ConditionEnum.IN.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("distributorIdInclude",  conditionsEntityExt.getValue());
                }else if (Objects.equals(ConditionEnum.NOIN.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("distributorIdNoIn",  conditionsEntityExt.getValue());
                }else if (Objects.equals(ConditionEnum.EMPTY.getSymbol(), conditionsEntityExt.getSymbol())){
                    params.put("distributorIdEmpty", "");
                }
            }else if (Objects.equals(conditionsEntityExt.getAttr(), "dataId")) {
                params.put("idIn", conditionsEntityExt.getValue());
            }
        }

        String nameLike = formDataListDTO.getNameLike();
        if (StringUtil.isNotEmpty(nameLike)) {
            params.put("nameLike", nameLike);
        }
        params.put("orderByStr", "add_time desc");

        List<WriteOffRecordEntity> entities = writeOffRecordModel.findEntities(params);
        paasFormDataEsListVO.setBottomPermissions(new ArrayList<>());
        if (entities.size() == 0) {
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            return paasFormDataEsListVO;
        }
        Integer count = writeOffRecordModel.getEntityCount(params);
        paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(count));
        List<Long> distributorAccountIds = new ArrayList<>();
        entities.forEach(item -> distributorAccountIds.add(item.getDistributorId()));
        List<DistributorAccountEntity> distributorAccountEntities = distributorAccountModel.getByIdIn(corpid, distributorAccountIds);
        Map<Long, String> distributorAccountMap = new HashMap<>();
        distributorAccountEntities.forEach(item -> distributorAccountMap.put(item.getId(), item.getName()));
        // 列表数据封装
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>(entities.size());
        for (WriteOffRecordEntity writeOffRecordEntity : entities) {
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setDataId(writeOffRecordEntity.getId());
            JSONObject data = new JSONObject();
            paasFormDataEntityExt.setData(data);
            data.put(WriteOffRecordEnum.ORDER_TIME.getAttr(), writeOffRecordEntity.getOrderTime());
            data.put(WriteOffRecordEnum.ORDER_NO.getAttr(), writeOffRecordEntity.getSerialNo());
            data.put(WriteOffRecordEnum.ORDER_STATUS.getAttr(), OrderStatusEnum.getByCode(writeOffRecordEntity.getOrderStatus()).getName());
            data.put(WriteOffRecordEnum.DISTRIBUTOR_ID.getAttr(), distributorAccountMap.getOrDefault(writeOffRecordEntity.getDistributorId(), ""));
            data.put(WriteOffRecordEnum.COUPON.getAttr(), writeOffRecordEntity.getData().getJSONArray(WriteOffRecordEnum.COUPON.getAttr()));
            paasFormDataEntityExt.setAddTime(writeOffRecordEntity.getAddTime());
            paasFormDataESList.add(paasFormDataEntityExt);
        }
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);

        // 列表排序
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        return paasFormDataEsListVO;
    }

    @Override
    public PaasFormDataEsListVO distributorCommunicate4Export(FormDataListDTO formDataListDTO) throws XbbException {
        formDataListDTO.setBusinessType(XbbRefTypeEnum.DISTRIBUTOR_COMMUNICATE.getCode());
        formDataListDTO.setSubBusinessType(XbbRefTypeEnum.DISTRIBUTOR_COMMUNICATE.getCode());
        AbstractWebDataAnalysisHandle abstractWebDataAnalysisHandle = webDataAnalysisFactory.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        return abstractWebDataAnalysisHandle.analysisData(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO costAdjustList(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.COST_ADJUST.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.COST_ADJUST.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.COST_ADJUST.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    @Override
    public PaasFormDataEsListVO knowledgeList(KnowledgeListDTO knowledgeListDTO) throws XbbException {
        if (!Objects.equals(knowledgeListDTO.getBusinessType(),XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = knowledgeListDTO.getConditions();
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(knowledgeListDTO.getSubBusinessType(),knowledgeListDTO.getCorpid(),knowledgeListDTO.getUserId(), knowledgeListDTO.getStatusFilter()));
        //UserEntity userEntity = new UserEntity();
        //BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        //saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.KNOWLEDGE_BASE.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        //saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.KNOWLEDGE_BASE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        knowledgeListDTO.setConditions(conditionList);
        return knowledgeDataService.listByEs(knowledgeListDTO);
    }

    @Override
    public List<DimensionViewPoJo> dimensionViewList(FormDataListDTO formDataListDTO) throws XbbException{
        Integer businessType = formDataListDTO.getBusinessType();
        List<DimensionViewPoJo> dimensionViewPoJos=new ArrayList<>(MultiDimensionViewEnum.values().length);
        List<MultiDimensionViewEnum> multiDimensionViewEnumList = MultiDimensionViewEnum.getByBusinessType(businessType);
        if(CollectionsUtil.isNotEmpty(multiDimensionViewEnumList)){
            for (MultiDimensionViewEnum dimensionViewEnum : multiDimensionViewEnumList) {
                DimensionViewPoJo dimensionViewPoJo=new DimensionViewPoJo();
                dimensionViewPoJo.setCode(dimensionViewEnum.getCode());
                dimensionViewPoJo.setView(dimensionViewEnum.getView());
                dimensionViewPoJo.setViewName(dimensionViewEnum.getViewName());
                dimensionViewPoJos.add(dimensionViewPoJo);
            }
        }
        return  dimensionViewPoJos;
    }

    /**
     * @Author: wujian
     * @Description: 获取待采购产品详情
     * @Date: 下午4:13 2021/9/13
     * @Param: [formDataListDTO]
     * @return: com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO
     **/
    @Override
    public WaitPurchaseProductVO getWaitPurchaseProductDetail(DetailTabDataGetDTO detailTabDataGetDTO) throws XbbException {
        String corpid = detailTabDataGetDTO.getCorpid();
        Long contractId = detailTabDataGetDTO.getDataId();
        Boolean isDingTalk = false;
        String platform = detailTabDataGetDTO.getPlatform();
        if (Objects.nonNull(platform) && Objects.equals(platform, PlatFormEnum.DINGTALK.getValue())) {
            isDingTalk = true;
        }
        boolean isEnglish = false;
        String locale = detailTabDataGetDTO.getLocale();
        if (Objects.equals(locale,"en_US")){
            isEnglish = true;
        }
        return getWaitDetail(corpid, contractId, null, isDingTalk, detailTabDataGetDTO.getLoginUser(), detailTabDataGetDTO.getUserId(),isEnglish);
    }


    /**
     * @Author: wujian
     * @Description: 获取web待采购产品详情&移动端产品视图详情
     * @Date: 下午4:13 2021/9/13
     * @Param: [formDataListDTO]
     * @return: com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO
     **/
    public WaitPurchaseProductVO getWaitDetail(String corpid, Long contractId, Long pid, boolean isDingtalkDetail, UserVO loginUser, String userId ,boolean isEnglish) throws XbbException {
        WaitPurchaseProductVO waitPurchaseProductVO = new WaitPurchaseProductVO();
        List<WaitPurchaseProductPojo> waitPurchaseProductList = new ArrayList<>();
        // 设置表头
        List<FieldAttrEntity> headList = handleWaitProductHead(isDingtalkDetail,isEnglish);
        waitPurchaseProductVO.setHeadList(headList);
        // 获取该合同下所有产品
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", corpid);
        params.put("del", 0);
        params.put("contractId", contractId);
        params.put("status",0);
        params.put("isProduce",0);
        if (isDingtalkDetail){
            params.put("id",pid);
        }
        params.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        List<ContractProductEntity> contractProductEntityList = contractProductModel.findEntitys(params);
        if(CollectionsUtil.isNotEmpty(contractProductEntityList)){
            List<String> onlyKeyList = new ArrayList<>();
            contractProductEntityList.forEach(item -> onlyKeyList.add(item.getId() + "_" + item.getProductId()));
            // 获取该合同下所有的采购数据
            // key=contractid_product_id  value = 采购数据
            Map<String, Double> purchaseByContractMap = saasListHelp.getPurchaseByContract(corpid, Collections.singletonList(contractId));
            // 获取采购结存表所有数据
            List<PurchaseBalanceEntity> purchaseBalanceEntityList = new ArrayList<>();
            if (CollectionsUtil.isNotEmpty(onlyKeyList)){
                purchaseBalanceEntityList = purchaseBalanceModel.findByOnlyKeys(corpid, onlyKeyList);
            }
            // 超发库存map key = contractid_productid  value=超发库存总量
            Map<String, Double> exceedStockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if  (CollectionsUtil.isNotEmpty(purchaseBalanceEntityList)){
                purchaseBalanceEntityList.forEach(item -> exceedStockMap.put(item.getOnlyKey(),item.getExceedStockNum()));
            }
            Set<Long> productIdSet = new HashSet<>();
            contractProductEntityList.forEach(item -> productIdSet.add(item.getProductId()));
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), productIdSet));
            boolQueryBuilder.filter(termQuery("del", 0));
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
            // 限制返回值
            List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA, "formId");
            Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
            Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
            List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
            productItems.forEach(item -> {
                if (!Objects.equals(item.getIsOther(), 1)) {
                    unitItemMap.put(item.getValue().toString(), item.getText());
                }
            });
            //关联产品的具体信息
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
            Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PaasFormDataEntityExt entity : paasFormDataEntityExtList) {
                productMap.put(entity.getDataId(), entity);
            }
            int accuary = 6;
            List<WaitPurchasePojo> waitPurchasePojoList = saasListHelp.getPurchaseSupplierByContract(corpid, Collections.singletonList(contractId));
            Map<Long, ProductEntityExt> productMap1 = saasListHelp.getProductMap(productIdSet, corpid);
            ContractEntityExt contractEntityExt = null;
            if (isDingtalkDetail){
                contractEntityExt = contractModel.getByKey(contractId, corpid);
            }
            for (ContractProductEntity contractProductEntity : contractProductEntityList) {
                Double rate = 1D;
                WaitPurchasePojo waitPurchasePojo = new WaitPurchasePojo();
                Long productId = contractProductEntity.getProductId();
                Long contractProductId = contractProductEntity.getId();
                if (!productMap.containsKey(productId)) {
                    continue;
                }
                JSONObject productData = new JSONObject();
                if (!productMap.isEmpty() && Objects.nonNull(productMap.get(productId))){
                    productData = productMap.get(productId).getData();

                    String onlyKey = contractProductId + "_" +productId;
                    if (CollectionsUtil.isNotEmpty(waitPurchasePojoList)){
                        waitPurchasePojoList.forEach(item ->{
                            if (Objects.equals(onlyKey,item.getOnlyKey())){
                                waitPurchasePojo.setOnlyKey(item.getOnlyKey());
                                waitPurchasePojo.setSupplierIdSet(item.getSupplierIdSet());
                                waitPurchasePojo.setPurchaseInstockNum(item.getPurchaseInstockNum());
                            }
                        });
                    }
                    double purchaseSumNum = 0D;
                    if(!purchaseByContractMap.isEmpty() && purchaseByContractMap.containsKey(onlyKey)){
                        purchaseSumNum = purchaseByContractMap.get(onlyKey);
                    }
                    // 超发库存总量
                    double exceedNum = 0D;
                    if (!exceedStockMap.isEmpty() && exceedStockMap.containsKey(onlyKey)){
                        exceedNum = exceedStockMap.get(onlyKey);
                    }
                    // 新公式: 建议采购量 = 合同总量 - 采购总量 - 超发库存总量
                    double shortageQuantity = Arith.sub(contractProductEntity.getProductNum(),Arith.add(purchaseSumNum,exceedNum));
                    if (shortageQuantity <= 0){
                        continue;
                    }
//                    if (Objects.nonNull(contractProductEntity.getBusinessUnit())) {
//                        List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(contractProductEntity.getGroupId());
//                        if (CollectionsUtil.isNotEmpty(unitItemPoJos)) {
//                            accuary = unitItemPoJos.get(0).getAccuracy();
//                        }
//                        contractProductEntity.setProductUnit(contractProductEntity.getBusinessUnit().toString());
//                        shortageQuantity = Arith.div(shortageQuantity, contractProductEntity.getRate(), accuary);
//                    }
                    WaitPurchaseProductPojo waitPurchaseProductPojo = new WaitPurchaseProductPojo();
                    waitPurchaseProductPojo.setParentId(productData.getLong(ProductEnum.PARENT_ID.getAttr()));
                    waitPurchaseProductPojo.setId(contractProductEntity.getId());
                    waitPurchaseProductPojo.setProductId(contractProductEntity.getId());
                    waitPurchaseProductPojo.setStockSearchId(contractProductEntity.getProductId());
                    waitPurchaseProductPojo.setName(productData.getString(ProductEnum.NAME.getAttr()));
                    waitPurchaseProductPojo.setSerialNo(contractProductEntity.getProductNo());
                    waitPurchaseProductPojo.setNum(shortageQuantity);
                    waitPurchaseProductPojo.setAdvisePurchaseNum(shortageQuantity);
                    //waitPurchaseProductPojo.setProductImgs(productData.getString(ProductEnum.PRODUCT_IMGS.getAttr()) == null ? new JSONArray() : productData.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()));
                    //处理图片
                    JSONArray thumbnail = new JSONArray();
                    ProductEntityExt productEntityExt = productMap1.get(productId);
                    if (productEntityExt != null) {
                        JSONArray productImgs = new JSONArray();
                        JSONObject data = productEntityExt.getData();
                        if (Objects.nonNull(data) && CollectionsUtil.isEmpty(data.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()))) {
                            data.put(ProductEnum.PRODUCT_IMGS.getAttr(), data.getJSONArray(ProductEnum.THUMBNAIL.getAttr()));
                        }
                        productImgs = productEntityExt.getData().getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr());
                        if (productImgs != null && !productImgs.isEmpty()) {
                            thumbnail.add(productImgs.getString(0));
                        }
                    }
                    waitPurchaseProductPojo.setProductImgs(thumbnail);
                    String unit = contractProductEntity.getProductUnit();
                    Long businessUnit = contractProductEntity.getBusinessUnit();
                    if (Objects.nonNull(businessUnit)){
                        unit = businessUnit.toString();
                        rate = contractProductEntity.getRate();
                    }
                    waitPurchaseProductPojo.setProductUnit(unitItemMap.getOrDefault(unit, Objects.nonNull(unit) && (!ItemUtil.isUUID(unit) || !RegexUtil.isOnePositiveInt(unit.toString())) ? unit : ""));
                    if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                        Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                        waitPurchaseProductPojo.setTransformUnitRate(groupItemsMap.get(productUnit));
                        MultiUnitItemPoJo multiUnitItemPJ = groupBaseUnitMap.get(productUnit);
                        String baseName = multiUnitItemPJ.getBaseName();
                        waitPurchaseProductPojo.setBaseProductUnit(baseName);
                        waitPurchaseProductPojo.setEnableMultiUnit(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                        if (!StringUtil.isDigital(unit) || Long.parseLong(unit) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                            MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                            if (Objects.nonNull(multiUnitItemPoJo)) {
//                                waitPurchaseProductPojo.setProductUnit(multiUnitItemPoJo.getBaseName());
                            }
                        }
                    }
                    waitPurchaseProductPojo.setSpecification(specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr())));
                    waitPurchaseProductPojo.setMemo(contractProductEntity.getMemo());
                    // 销售数量
                    waitPurchaseProductPojo.setMarketNum(contractProductEntity.getProductNum() == null ? null : Arith.div(contractProductEntity.getProductNum(),rate));
                    // 已采购数量
                    waitPurchaseProductPojo.setPurchaseNum(purchaseByContractMap.get(onlyKey) == null ? null : Arith.div(purchaseByContractMap.get(onlyKey),rate));
                    // 已入库数量
                    waitPurchaseProductPojo.setInstockNum(waitPurchasePojo.getPurchaseInstockNum() == null ? null : Arith.div(waitPurchasePojo.getPurchaseInstockNum(),rate));
                    // 出库数量
                    waitPurchaseProductPojo.setOutstockNum(contractProductEntity.getOutstockNum() == null ? null : Arith.div(contractProductEntity.getOutstockNum(),rate));
                    // 未出库数量
                    waitPurchaseProductPojo.setWaitOutstockNum(Arith.div(Arith.sub(contractProductEntity.getProductNum(),contractProductEntity.getOutstockNum()),rate));
                    //供应商处理
                    List<SupplierProductEntity> supplierProductList = supplierProductModel.getSupplierProductByParentId(corpid, contractProductEntity.getParentId());
                    JSONArray supplierArr = new JSONArray();
                    Map<Long, String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (SupplierProductEntity supplierProductEntity : supplierProductList) {
                        supplierNameMap.put(supplierProductEntity.getSupplierId(), supplierProductEntity.getSupplierName());
                    }
                    for (Map.Entry<Long, String> entry : supplierNameMap.entrySet()) {
                        JSONObject supplierObj = new JSONObject();
                        supplierObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, entry.getKey());
                        supplierObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, entry.getValue());
                        supplierObj.put(StringConstant.BUSINESS_TYPE,XbbRefTypeEnum.SUPPLIER.getCode());
                        supplierObj.put(StringConstant.SAAS_MARK,SaasMarkEnum.SAAS.getCode());
                        supplierArr.add(supplierObj);
                    }
                    // 供应商
                    waitPurchaseProductPojo.setSupplier(supplierArr);
                    waitPurchaseProductPojo.setPurchaseDetail("查看全部");
                    waitPurchaseProductPojo.setStockSearch("查看全部");
                    if(isEnglish){
                        waitPurchaseProductPojo.setPurchaseDetail("view all");
                        waitPurchaseProductPojo.setStockSearch("view all");
                    }
                    waitPurchaseProductPojo.setCreatorId(productMap.get(productId).getCreatorId());
                    waitPurchaseProductPojo.setOwnerId(productMap.get(productId).getOwnerId());
                    if (isDingtalkDetail && Objects.nonNull(contractEntityExt) && Objects.nonNull(contractEntityExt.getData())){
                        waitPurchaseProductPojo.setContractNo(contractEntityExt.getSerialNo());
                        waitPurchaseProductPojo.setContractName(contractEntityExt.getData().getString(ContractEnum.NAME.getAttr()));
                        waitPurchaseProductPojo.setCustomer(contractEntityExt.getData().getString(ContractEnum.LINK_CUSTOMER_HIDE.getAttr()));
                        waitPurchaseProductPojo.setAddTime(contractEntityExt.getAddTime());
                        waitPurchaseProductPojo.setUpdateTime(contractEntityExt.getUpdateTime());
                        waitPurchaseProductPojo.setCreatorId(contractEntityExt.getCreatorId());
                    }
                    waitPurchaseProductList.add(waitPurchaseProductPojo);
                }
            }
        }
        // 要控制可见权限就要拿到系统中的解释
        // 此表单由产品 合同 采购合同
        List<FieldAttrEntity> headListExplain = new ArrayList<>();
        PaasFormExplainEntity contractExplains = null;
        Map<String, Object> paasFormParam = new HashMap<>();
        paasFormParam.put("corpid", corpid);
        paasFormParam.put("enable", 1);
        paasFormParam.put("del", 0);
        paasFormParam.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        paasFormParam.put("businessType", XbbRefTypeEnum.CONTRACT.getCode());
        paasFormParam.put("orderByStr", "sort ASC ");
        List<PaasFormEntity> paasFormEntityList = paasFormModel.findEntity(paasFormParam);
        if (CollectionsUtil.isNotEmpty(paasFormEntityList)){
            Long formId = paasFormEntityList.get(0).getId();
            contractExplains = paasFormExplainModel.getByFormId(formId, corpid);
        }
        if (Objects.nonNull(contractExplains)){
            List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(contractExplains.getExplains(), FieldAttrEntity.class);
            // 需要用到合同产品的备注 单位 数量 未出库数量控制字段可见
            // 拿合同产品解释
            if(CollectionsUtil.isNotEmpty(fieldAttrEntityList)){
                for (FieldAttrEntity fieldAttrEntity : fieldAttrEntityList) {
                    if (Objects.equals(ContractEnum.NAME.getAttr(),fieldAttrEntity.getAttr())
                       || Objects.equals(ContractEnum.CONTRACT_NO.getAttr(),fieldAttrEntity.getAttr())
                       || Objects.equals(ContractEnum.ADD_TIME.getAttr(),fieldAttrEntity.getAttr())
                       || Objects.equals(ContractEnum.UPDATE_TIME.getAttr(),fieldAttrEntity.getAttr())
                       || Objects.equals(ContractEnum.CREATOR_ID.getAttr(),fieldAttrEntity.getAttr())
                       || Objects.equals(ContractEnum.LINK_CUSTOMER.getAttr(),fieldAttrEntity.getAttr()) ){
                        headListExplain.add(fieldAttrEntity);
                    }
                    if (Objects.equals(ContractEnum.PRODUCT.getAttr(),fieldAttrEntity.getAttr())) {
                        List<FieldAttrEntity> items = (List<FieldAttrEntity>) fieldAttrEntity.getSubForm().getItems();
                        if (CollectionsUtil.isNotEmpty(items)){
                            items.forEach(item  ->{
                                if (Objects.equals(item.getAttr(),ContractProductEnum.UNIT.getAttr()) ||
                                        Objects.equals(item.getAttr(),ContractProductEnum.MEMO.getAttr()) ||
                                        Objects.equals(item.getAttr(),ContractProductEnum.NUM.getAttr()) ||
                                        Objects.equals(item.getAttr(),ContractProductEnum.OUTSTOCK_NUM.getAttr()) ||
                                        Objects.equals(item.getAttr(),ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr())){
                                    headListExplain.add(item);
                                }
                            });
                        }
                    }
                }
            }
        }
        Map<String,Object> contractUserparam = new HashMap<>();
        contractUserparam.put("corpid",corpid);
        contractUserparam.put("del",0);
        contractUserparam.put("contractIdIn",Collections.singletonList(contractId));
        List<ContractUserEntity> contractUserEntityList = contractUserModel.findEntitys(contractUserparam);
        // 负责人Map
        Map<Long,List<String>> ownerMap = new HashMap<>();
        // 协同人Map
        Map<Long,List<String>> coUserMap = new HashMap<>();
        // 封装合同数据的负责人协同人数据
        if (CollectionsUtil.isNotEmpty(contractUserEntityList)){
            for (ContractUserEntity contractUserEntity : contractUserEntityList) {
                Integer isMain = contractUserEntity.getIsMain();
                if (Objects.equals(isMain,1)){
                    if (ownerMap.containsKey(contractId)){
                        List<String> list = ownerMap.get(contractId);
                        list.add(contractUserEntity.getUserId());
                        ownerMap.put(contractId,list);
                    }else{
                        List<String> owenList = new ArrayList<>();
                        owenList.add(contractUserEntity.getUserId());
                        ownerMap.put(contractId,owenList);
                    }

                }else {
                    if (coUserMap.containsKey(contractId)){
                        List<String> list = coUserMap.get(contractId);
                        list.add(userId);
                        coUserMap.put(contractId,list);
                    }else{
                        List<String> coList = new ArrayList<>();
                        coList.add(userId);
                        coUserMap.put(contractId,coList);
                    }
                }
            }
        }
        PaasFormExplainEntity productExplains = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        if (Objects.nonNull(productExplains)){
            List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(productExplains.getExplains(), FieldAttrEntity.class);
            // 获取产品供应商解释
            if(CollectionsUtil.isNotEmpty(fieldAttrEntityList)){
                fieldAttrEntityList.forEach(item ->{
                    if (Objects.equals(ProductEnum.NAME.getAttr(),item.getAttr())){
                        item.setAttr("productName");
                        headListExplain.add(item);
                    }
                    if (Objects.equals(ProductEnum.SERIALNO.getAttr(),item.getAttr())){
                        item.setAttr("productSerialNo");
                        headListExplain.add(item);
                    }
                    if(Objects.equals(ProductEnum.SUPPLIER.getAttr(),item.getAttr())
                    || Objects.equals(ProductEnum.PRODUCT_IMGS.getAttr(),item.getAttr())
                    || Objects.equals(ProductEnum.SPECIFICATION.getAttr(),item.getAttr())){
                        headListExplain.add(item);
                    }
                });
            }
        }
        // 处理数据高级不可见
        saasListHelp.parseCanseeData(waitPurchaseProductList,headListExplain,loginUser,ownerMap,coUserMap);
        waitPurchaseProductVO.setWaitPurchaseProductList(waitPurchaseProductList);
        return waitPurchaseProductVO;
    }
    @Override
    public WaitPurchaseDetailVO getorderOnPinDetail(OrderOnPinDTO orderOnPinDTO) throws XbbException {
        boolean isEnglish = false;
        String locale = orderOnPinDTO.getLocale();
        if (Objects.equals(locale,"en_US")){
            isEnglish = true;
        }
        WaitPurchaseDetailVO waitPurchaseDetailVO = new WaitPurchaseDetailVO();
        waitPurchaseDetailVO.setHeadList(handleWaitPurchaseDetailHead(isEnglish));
        String corpid = orderOnPinDTO.getCorpid();
        Long contractId = orderOnPinDTO.getContractId();
        Long productId = orderOnPinDTO.getProductId();
        ContractProductEntity contractProductEntity = contractProductModel.getByKey(productId,corpid);

        List<WaitPurchaseDetailPojo> waitPurchaseDetailPojoList = new ArrayList<>();
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("contractId",contractId);
        param.put("contractProductId",productId);
        param.put("del",DelEnum.NORMAL.getDel());
        param.put("orderByStr","update_time desc");
        // 跟该合同产品所关联的所有采购合同产品数据
        List<PurchaseProductEntity> purchaseProductEntityList = purchaseProductModel.findEntitys(param);
        List<Long> purchaseIdList = new ArrayList<>();
        purchaseProductEntityList.forEach(item ->purchaseIdList.add(item.getPurchaseSheetId()));
        // key=采购合同ID value=采购合同实体
        Map<Long, PurchaseEntityExt> purchaseEntityExtMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
        productItems.forEach(item -> {
            if (!Objects.equals(item.getIsOther(), 1)) {
                unitItemMap.put(item.getValue().toString(), item.getText());
            }
        });
        // key->单位ID value->单位组ID
        Map<Long,Long> businessGroupMap = new HashMap<>();
        for (Map.Entry<Long, List<UnitItemPoJo>> unitItemPojo : groupItemsMap.entrySet()) {
            List<UnitItemPoJo> value = unitItemPojo.getValue();
            value.forEach(item->businessGroupMap.put(item.getValue(),unitItemPojo.getKey()));
        }
        // 采购合同数据封装
        if (CollectionsUtil.isNotEmpty(purchaseIdList)){
            // 查询所有采购合同封装map方便下面封装编号名称时取
            List<PurchaseEntityExt> purchaseEntityExtList = purchaseModel.getPurchaseListByIdIn(corpid, purchaseIdList);
            if(CollectionsUtil.isNotEmpty(purchaseEntityExtList)){
                purchaseEntityExtList.forEach(item -> purchaseEntityExtMap.put(item.getId(),item));
                // 循环所有采购合同产品数据封装实体
                for (PurchaseProductEntity purchaseProductEntity : purchaseProductEntityList) {
                    WaitPurchaseDetailPojo waitPurchaseDetailPojo = new WaitPurchaseDetailPojo();
                    Long purchaseId = purchaseProductEntity.getPurchaseSheetId();
                    PurchaseEntityExt purchaseEntityExt = purchaseEntityExtMap.get(purchaseId);
                    waitPurchaseDetailPojo.setDate(purchaseEntityExt.getAddTime());
                    waitPurchaseDetailPojo.setPurchaseNo(purchaseEntityExt.getSerialNo());
                    waitPurchaseDetailPojo.setPurchaseName(purchaseEntityExt.getData().getString(PurchaseEnum.PURCHASE_NAME.getAttr()));
                    waitPurchaseDetailPojo.setPurchaseNum(purchaseProductEntity.getProductNum());
                    waitPurchaseDetailPojo.setInstockNum(purchaseProductEntity.getInstockNum());
                    if (Objects.nonNull(purchaseProductEntity.getBusinessUnit())){
                        String unit = purchaseProductEntity.getProductUnit();
                        waitPurchaseDetailPojo.setUnit(unitItemMap.getOrDefault(unit, Objects.nonNull(unit) && (!ItemUtil.isUUID(unit) || !RegexUtil.isOnePositiveInt(unit.toString())) ? unit : ""));
                        waitPurchaseDetailPojo.setTransformUnitRate(groupItemsMap.getOrDefault(businessGroupMap.get(Long.valueOf(unit)),new ArrayList<>()));
                    }
                    waitPurchaseDetailPojoList.add(waitPurchaseDetailPojo);
                }
            }
        }
        // 销售出库数据封装
        Map<String,Object> contractParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        contractParam.put("corpid",corpid);
        contractParam.put("refId",contractId);
        contractParam.put("type", OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode());
        List<OutstockEntityExt> contractOutstockList = outstockModel.getByContractId(contractParam);
        List<Long> contractOutstockIdlist = new ArrayList<>();
        // key=销售出库单ID  value=销售出库单实体
        Map<Long,OutstockEntityExt> outstockEntityExtMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isNotEmpty(contractOutstockList)){
            contractOutstockList.forEach(item ->{
                contractOutstockIdlist.add(item.getId());
                outstockEntityExtMap.put(item.getId(),item);
            });
        }
        List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.getProductsByOutstockIdIn(corpid, contractOutstockIdlist);
        // key=销售出库单ID  销售出库产品实体
        Map<Long,OutstockProductEntity> outstockProductEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Double outstockNum = 0D;
        if (CollectionsUtil.isNotEmpty(outstockProductEntityList)){
            for (OutstockProductEntity outstockProductEntity : outstockProductEntityList) {
                // 该合同下所有销售出库单下的销售出库产品
                if (Objects.equals(outstockProductEntity.getRefProductId(),productId)){
                   outstockProductEntityMap.put(outstockProductEntity.getOutWarehouseId(),outstockProductEntity);
                }
            }
            if (!outstockProductEntityMap.isEmpty()){
                for (Map.Entry<Long, OutstockProductEntity> outstockProductEntityEntry : outstockProductEntityMap.entrySet()) {
                    Long contractOutstockId = outstockProductEntityEntry.getKey();
                    if (!outstockEntityExtMap.isEmpty() && outstockEntityExtMap.containsKey(contractOutstockId)){
                        OutstockProductEntity outstockProductEntity = outstockProductEntityEntry.getValue();
                        OutstockEntityExt outstockEntityExt = outstockEntityExtMap.get(contractOutstockId);
                        WaitPurchaseDetailPojo waitPurchaseDetailPojo = new WaitPurchaseDetailPojo();
                        waitPurchaseDetailPojo.setDate(outstockEntityExt.getAddTime());
                        waitPurchaseDetailPojo.setContractOutstockNo(outstockEntityExt.getSerialNo());
                        waitPurchaseDetailPojo.setOutstockNum(outstockProductEntity.getProductNum());
                        waitPurchaseDetailPojoList.add(waitPurchaseDetailPojo);
                        outstockNum +=outstockProductEntity.getProductNum();
                        if (Objects.nonNull(outstockProductEntity.getBusinessNum())){
                            String unit = outstockProductEntity.getProductUnit();
                            waitPurchaseDetailPojo.setUnit(unitItemMap.getOrDefault(unit, Objects.nonNull(unit) && (!ItemUtil.isUUID(unit) || !RegexUtil.isOnePositiveInt(unit.toString())) ? unit : ""));
                            waitPurchaseDetailPojo.setTransformUnitRate(groupItemsMap.getOrDefault(businessGroupMap.get(Long.valueOf(unit)),new ArrayList<>()));
                        }
                    }
                }
            }
        }
        waitPurchaseDetailVO.setWaitPurchaseDetailPojoList(waitPurchaseDetailPojoList);
        waitPurchaseDetailVO.setWaitOutstockNum(0D);
        if (Objects.nonNull(contractProductEntity) && Objects.nonNull(contractProductEntity.getProductNum()) && Objects.nonNull(outstockNum)){
            waitPurchaseDetailVO.setWaitOutstockNum(Arith.sub(contractProductEntity.getProductNum(),outstockNum));
        }
        if(Objects.nonNull(contractProductEntity) && Objects.nonNull(contractProductEntity.getBusinessUnit())){
            String unit = contractProductEntity.getProductUnit();
            waitPurchaseDetailVO.setUnit(unitItemMap.getOrDefault(unit, Objects.nonNull(unit) && (!ItemUtil.isUUID(unit) || !RegexUtil.isOnePositiveInt(unit.toString())) ? unit : ""));
            waitPurchaseDetailVO.setTransformUnitRate(groupItemsMap.getOrDefault(businessGroupMap.get(Long.valueOf(unit)),new ArrayList<>()));
        }
        return waitPurchaseDetailVO;
    }

    @Override
    public ListAppVO formatWaitContractOutstockDetail(FormDataGetDTO formDataGetDTO) throws XbbException {
        List<AppListPojo> appListPojos = new ArrayList<>();
        String corpid = formDataGetDTO.getCorpid();
        Long contractId=formDataGetDTO.getDataId();
        List<Long> dataIdList = new ArrayList<>();
        dataIdList.add(contractId);
        //获取合同数据
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), dataIdList));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
        XbbAggregatedPage<PaasFormDataEntity> esEntities = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, PaasFormDataEntity.class, Arrays.asList(FieldTypeEnum.DATAID.getAlias(), FieldTypeEnum.SERIALNO.getAlias(),"data","ownerId","coUserId","addTime","updateTime","creatorId"), 1, dataIdList.size(), null);
        Map<Long, PaasFormDataEntity> contractMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntity entity : esEntities.getContent()) {
            contractMap.put(entity.getDataId(), entity);
        }
        //获取合同产品信息
        Set<Long> productIdSet = new HashSet<>();
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        map.put("del", DelEnum.NORMAL.getDel());
        map.put("contractIdIn", dataIdList);
        map.put("status",0);
        map.put("surplusNum",0);
        if (Objects.nonNull(formDataGetDTO.getLinkId())){
            map.put("id", formDataGetDTO.getLinkId());
        }
        List<ContractProductEntity> contractProductEntityList = contractProductModel.findEntitys(map);
        for (ContractProductEntity entity : contractProductEntityList) {
            productIdSet.add(entity.getProductId());
            productIdSet.add(entity.getParentId());
        }
        //获取待出库数量
        Map<String, Double> productEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("refIdIn", dataIdList);
        param.put("type", OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode());
        param.put("del", 0);
        param.put("columns","ref_id,product_id,ref_product_id,product_num");
        param.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.findEntitys(param);
        for (OutstockProductEntity entity : outstockProductEntityList){
            String key;
            if (Objects.isNull(entity.getRefProductId())){
                key = entity.getRefId() + "_" + entity.getProductId();
            }else {
                key = entity.getRefId() + "_" + entity.getProductId() + "_" + entity.getRefProductId();
            }
            Double num = productEntityMap.getOrDefault(key,0D);
            num += entity.getProductNum();
            productEntityMap.put(key,num);
        }
        Iterator<ContractProductEntity> iterator = contractProductEntityList.iterator();
        while (iterator.hasNext()) {
            ContractProductEntity entity = iterator.next();
            String key = entity.getContractId() + "_" + entity.getProductId() + "_" + entity.getId();
            //先匹配新数据
            if (!productEntityMap.containsKey(key)) {
                //在匹配老数据
                key = entity.getContractId() + "_" + entity.getProductId();
                if (!productEntityMap.containsKey(key)) {
                    entity.setWaitOutStockNum(entity.getProductNum());
                    continue;
                }
            }
            Double outstockNum = productEntityMap.get(key);
            double productNum = entity.getProductNum() == null ? 0D : entity.getProductNum();
            double leftProductNum = Arith.sub(productNum, outstockNum);
            if (leftProductNum < 0.00000001 ) {
                productEntityMap.put(key,0D);
            } else {
                productEntityMap.put(key,leftProductNum);
            }
            entity.setWaitOutStockNum(productEntityMap.getOrDefault(key,0D));
        }
        //获取产品ES数据
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolProductQueryBuilder = boolQuery();
        boolProductQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolProductQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), productIdSet));
        boolProductQueryBuilder.filter(termQuery("del", 0));
        boolProductQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        sourceBuilder.query(boolProductQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, productIdSet.size());
        searchRequest.source(sourceBuilder);
        //关联产品的具体信息
        XbbAggregatedPage<PaasFormDataEntityExt> esProdcutEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PaasFormDataEntityExt> productPaasFormDatas=new ArrayList<>();
        for (PaasFormDataEntityExt entity : esProdcutEntities.getContent()) {
            productMap.put(entity.getDataId(), entity);
            productPaasFormDatas.add(entity);
        }
        //处理权限
        StringBuffer coUserListStr = new StringBuffer();
        StringBuffer mainUserListStr = new StringBuffer();
        List<FieldAttrEntity> explainList=contractService.processContractAndproductExplain(productPaasFormDatas,contractMap,contractProductEntityList,formDataGetDTO.getLoginUser(),corpid,formDataGetDTO.getFormId(),formDataGetDTO.getUserId(), coUserListStr, mainUserListStr);
        Boolean isDateTime=false;
        for (FieldAttrEntity fieldAttrEntity:explainList){
            if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.SIGN_TIME.getAttr())){
                if (Objects.equals(fieldAttrEntity.getDateType(), DateTimeEnum.DATETIME.getType())){
                    isDateTime=true;
                    break;
                }
            }
        }
        //获取合同ES数据
        PaasFormDataEntity contractDataEntity=contractMap.get(contractId);
        JSONObject contractData=contractDataEntity.getData();
        //组装返回数据
        //多单位数据
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        //普通单位数据
        Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
        productItems.forEach(item -> unitItemMap.put(item.getValue().toString(), item.getText()));
        JSONArray explains = new JSONArray();
        JSONObject others = new JSONObject();
        List<WaitOutProductDTO> waitOutProductDtos=new ArrayList<>();
        String creatorId =contractDataEntity.getCreatorId();
        String ownerId = contractDataEntity.getOwnerId();
        Map<String, String> userIdAndNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //获取name
        List<String> userIds = new ArrayList<>();
        if (Objects.nonNull(creatorId)){
            userIds.add(creatorId);
        }
        if (Objects.nonNull(ownerId)){
            userIds.add(ownerId);
        }
        if (!userIds.isEmpty()){
            Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paramMap.put(ParameterConstant.LEAVE_MARKS,1);
            paramMap.put("corpid",corpid);
            //paramMap.put("del",0);
            paramMap.put("userIdIn",userIds);
            List<UserEntity> userEntities = userModel.findEntitys(paramMap);
            for (UserEntity entity : userEntities) {
                userIdAndNameMap.put(entity.getUserId(), entity.getName());
            }
        }
        //组装产品数据
        if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(),formDataGetDTO.getBusinessType())){
            Long addTime =contractDataEntity.getAddTime();
            String addTimeShow="";
            if (Objects.nonNull(addTime)){
                String addTimeStr = DateTimeUtil.getStringEpochSecond(addTime, DateTimeUtil.SDFYMDHM);
                addTimeShow = addTimeStr == null ? "--" : addTimeStr;
            }
            Long updateTime = contractDataEntity.getUpdateTime();
            String updateTimeShow="";
            if (Objects.nonNull(updateTime)){
                String updateTimeStr = DateTimeUtil.getStringEpochSecond(updateTime, DateTimeUtil.SDFYMDHM);
                updateTimeShow = updateTimeStr == null ? "--" : updateTimeStr;
            }
            ContractProductEntity entity=contractProductEntityList.get(0);
            PaasFormDataEntityExt productEntity=productMap.get(entity.getProductId());
            JSONObject productData=productEntity.getData();
            //待出库数量
            Double waitOutNum = entity.getWaitOutStockNum();
            //多单位处理
            if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                others.put("transformUnitRate",groupItemsMap.get(productUnit));
                others.put("enableMultiUnit",productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                JSONObject businessUnit = new JSONObject();
                businessUnit.put("text", unitItemMap.getOrDefault(entity.getBusinessUnit().toString(), ""));
                businessUnit.put("value", entity.getBusinessUnit());
                others.put("businessUnit",businessUnit);
            }else {
                others.put("enableMultiUnit",productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
            }
            others.put("formId",contractDataEntity.getFormId());
            others.put("menuId",contractDataEntity.getMenuId());
            others.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.CONTRACT.getCode());
            others.put(StringConstant.DATA_ID, contractId);
            others.put("sourceBusinessType", XbbRefTypeEnum.PRODUCT.getCode());
            others.put("productId",entity.getProductId());
            others.put("linkId", entity.getId());
            others.put("productName",entity.getProductName());
            if (Objects.nonNull(entity.getProductThumbnail()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(entity.getProductThumbnail()))) {
                others.put("productImage", JSONArray.parseArray(entity.getProductThumbnail()));
            } else {
                if (Objects.nonNull(productMap.get(entity.getParentId()))) {
                    PaasFormDataEntityExt parentEntity=productMap.get(entity.getParentId());
                    JSONArray productImgs = FastJsonHelper.getJsonArrOrDefaultFromFormData(parentEntity.getData(), ProductEnum.PRODUCT_IMGS.getAttr(), new JSONArray());
                    others.put("productImage", productImgs);
                } else {
                    others.put("productImage", new JSONArray());
                }
            }
            String contractName = FastJsonHelper.getStringOrDefault(contractData,ContractEnum.NAME.getAttr(),"");
            Long signTime =contractData.getLong(ContractEnum.SIGN_TIME.getAttr());
            String signTimeShow="";
            if (Objects.nonNull(signTime)){
                if (isDateTime){
                    String signTimeStr = DateTimeUtil.getStringEpochSecond(signTime, DateTimeUtil.SDFYMDHM);
                    signTimeShow = signTimeStr == null ? "--" : signTimeStr;
                }else {
                    String signTimeStr = DateTimeUtil.getStringEpochSecond(signTime, DateTimeUtil.SDFDate);
                    signTimeShow = signTimeStr == null ? "--" : signTimeStr;
                }
            }
            if (Objects.equals(formDataGetDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                String status="";
                //LOG.info("合同状态"+contractData.getString(ContractEnum.STATUS.getAttr()));
                if (Objects.nonNull(OrderStatusEnum.getByCode(contractData.getString(OrderEnum.STATUS.getAttr())))){
                    status = OrderStatusEnum.getByCode(contractData.getString(OrderEnum.STATUS.getAttr())).getName();
                }else if(StringUtil.isNotEmpty(contractData.getString(OrderEnum.STATUS.getAttr()))){
                    status =OrderStatusEnum.PENDING_ORDER_REVIEW.getName();
                }
                String linkDistributor = contractData.getString(ContractEnum.LINK_CUSTOMER_HIDE.getAttr());
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.SPECIFICATION.getAttrName(), specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()))));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.ORDER_NO.getAttrName(), contractDataEntity.getSerialNo()));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.LINK_DISTRIBUTOR.getAttrName(), linkDistributor));
                if (Objects.nonNull(entity.getProductUnit())) {
                    if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                        waitOutNum=Arith.div(waitOutNum,entity.getRate());
                    }
                }
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName(), waitOutNum));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.SERIALNO.getAttrName(), productEntity.getSerialNo()));
                if (Objects.nonNull(entity.getProductUnit())) {
                    if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                        Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                        explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), unitItemMap.getOrDefault(entity.getBusinessUnit().toString(), "")));
                    } else {
                        explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), unitItemMap.getOrDefault(productData.get(ProductEnum.UNIT.getAttr()), "")));
                    }
                } else {
                    explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), ""));
                }
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,ProductEnum.STOCK.getAttrName(),productData.get(ProductEnum.STOCK.getAttr())));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,RelativeProductEnum.MEMO.getAttrName(),entity.getMemo()));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.NAME.getAttrName(),contractName));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.STATUS.getAttrName(), status));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.SIGN_TIME.getAttrName(), signTimeShow));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.CREATOR_ID.getAttrName(), userIdAndNameMap.get(creatorId) == null ? "" : userIdAndNameMap.get(creatorId)));
                if (mainUserListStr.length() > 0 ){
                    explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.OWNER_ID.getAttrName(),mainUserListStr));
                }else {
                    explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.OWNER_ID.getAttrName(),userIdAndNameMap.get(ownerId) == null ? "":userIdAndNameMap.get(ownerId)));
                }
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.MINOR_USER.getAttrName(), coUserListStr));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.ADD_TIME.getAttrName(), addTimeShow));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.UPDATE_TIME.getAttrName(), updateTimeShow));
            } else {
                String status="";
                //LOG.info("合同状态"+contractData.getString(ContractEnum.STATUS.getAttr()));
                if (Objects.nonNull(ContractStatusEnum.getByCode(contractData.getString(ContractEnum.STATUS.getAttr())))){
                    status = ContractStatusEnum.getByCode(contractData.getString(ContractEnum.STATUS.getAttr())).getName();
                }else if (StringUtil.isNotEmpty(contractData.getString(ContractEnum.STATUS.getAttr()))){
                    status =ContractStatusEnum.SIGNING.getName();
                }
                String linkCustomer = contractData.getString(ContractEnum.LINK_CUSTOMER_HIDE.getAttr());
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,ProductEnum.SPECIFICATION.getAttrName(),specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()))));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.CONTRACT_NO.getAttrName(), contractDataEntity.getSerialNo()));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.LINK_CUSTOMER.getAttrName(), linkCustomer));
                if (Objects.nonNull(entity.getProductUnit())) {
                    if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                        waitOutNum=Arith.div(waitOutNum,entity.getRate());
                    }
                }
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName(),waitOutNum));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,ProductEnum.SERIALNO.getAttrName(),productEntity.getSerialNo()));
                if (Objects.nonNull(entity.getProductUnit())) {
                    if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                        Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                        explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), unitItemMap.getOrDefault(entity.getBusinessUnit().toString(), "")));
                    } else {
                        explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), unitItemMap.getOrDefault(productData.get(ProductEnum.UNIT.getAttr()), "")));
                    }
                } else {
                    explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), ""));
                }
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,ProductEnum.STOCK.getAttrName(),productData.get(ProductEnum.STOCK.getAttr())));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, RelativeProductEnum.MEMO.getAttrName(),entity.getMemo()));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.NAME.getAttrName(),contractName));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.STATUS.getAttrName(), status));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.SIGN_TIME.getAttrName(), signTimeShow));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.CREATOR_ID.getAttrName(), userIdAndNameMap.get(creatorId) == null ? "" : userIdAndNameMap.get(creatorId)));
                if (mainUserListStr.length() > 0 ){
                    explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.OWNER_ID.getAttrName(),mainUserListStr));
                }else {
                    explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.OWNER_ID.getAttrName(),userIdAndNameMap.get(ownerId) == null ? "":userIdAndNameMap.get(ownerId)));
                }
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.MINOR_USER.getAttrName(), coUserListStr));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.ADD_TIME.getAttrName(), addTimeShow));
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.UPDATE_TIME.getAttrName(), updateTimeShow));

            }
            appListPojos.add(new AppListPojo(contractDataEntity.getId(), contractName, explains, null, null, others));
        }else {
            Long addTime =contractDataEntity.getAddTime();
            String addTimeShow="";
            if (Objects.nonNull(addTime)){
                String addTimeStr = DateTimeUtil.getStringEpochSecond(addTime, DateTimeUtil.SDFYMDHM);
                addTimeShow = addTimeStr == null ? "--" : addTimeStr;
            }
            Long updateTime = contractDataEntity.getUpdateTime();
            String updateTimeShow="";
            if (Objects.nonNull(updateTime)){
                String updateTimeStr = DateTimeUtil.getStringEpochSecond(updateTime, DateTimeUtil.SDFYMDHM);
                updateTimeShow = updateTimeStr == null ? "--" : updateTimeStr;
            }
        for (ContractProductEntity entity : contractProductEntityList) {
            JSONArray products = new JSONArray();
            PaasFormDataEntityExt productEntity=productMap.get(entity.getProductId());
            WaitOutProductDTO waitOutProductDTO =new WaitOutProductDTO();
            JSONObject productData=productEntity.getData();
            //待出库数量
            Double waitOutNum = entity.getWaitOutStockNum();
            String productName = productData.getString(ProductEnum.NAME.getAttr());
          /*  products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,StringConstant.DATA_ID,entity.getProductId()));
            products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,ProductEnum.PRODUCT_IMGS.getAttrName(),entity.getProductThumbnail()));
            products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,ProductEnum.NAME.getAttrName(),productName));*/
            products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,ProductEnum.SERIALNO.getAttrName(),productEntity.getSerialNo()));
            products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.SPECIFICATION.getAttrName(), specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()))));
            //多单位处理
            if (Objects.nonNull(entity.getProductUnit())) {
                if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                    Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                    JSONObject businessUnit = new JSONObject();
                    businessUnit.put("text", unitItemMap.getOrDefault(entity.getBusinessUnit().toString(), ""));
                    businessUnit.put("value", entity.getBusinessUnit());
                    waitOutProductDTO.setBusinessUnit(businessUnit);
                    waitOutProductDTO.setTransformUnitRate(groupItemsMap.get(productUnit));
                    //MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                    products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), unitItemMap.getOrDefault(entity.getBusinessUnit().toString(), "")));
                    waitOutNum=Arith.div(waitOutNum,entity.getRate());
                } else {
                    products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), unitItemMap.getOrDefault(productData.get(ProductEnum.UNIT.getAttr()), "")));
                }
            } else {
                products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ProductEnum.UNIT.getAttrName(), ""));
            }
            products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName(),waitOutNum));
            products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,ProductEnum.STOCK.getAttrName(),productData.get(ProductEnum.STOCK.getAttr())));
            products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,RelativeProductEnum.MEMO.getAttrName(),entity.getMemo()));
            waitOutProductDTO.setProductId(entity.getProductId());
            if (Objects.nonNull(entity.getProductThumbnail()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(entity.getProductThumbnail()))){
                waitOutProductDTO.setProductImage(JSONArray.parseArray(entity.getProductThumbnail()));
            }else {
                if (Objects.nonNull(productMap.get(entity.getParentId()))) {
                    PaasFormDataEntityExt parentEntity=productMap.get(entity.getParentId());
                    JSONArray productImgs = FastJsonHelper.getJsonArrOrDefaultFromFormData(parentEntity.getData(), ProductEnum.PRODUCT_IMGS.getAttr(), new JSONArray());
                    waitOutProductDTO.setProductImage(productImgs);
                } else {
                    waitOutProductDTO.setProductImage(new JSONArray());
                }
            }
            waitOutProductDTO.setEnableMultiUnit(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
            waitOutProductDTO.setProductName(productName);
            waitOutProductDTO.setLinkId(entity.getId());
            waitOutProductDTO.setProductInfo(products);
            waitOutProductDtos.add(waitOutProductDTO);
        }
        others.put("waitStockProcduct",waitOutProductDtos);
        others.put("formId",contractDataEntity.getFormId());
        others.put("menuId",contractDataEntity.getMenuId());
        others.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.CONTRACT.getCode());
        others.put(StringConstant.DATA_ID, contractId);
        others.put("sourceBusinessType", XbbRefTypeEnum.PRODUCT.getCode());
        String contractName = contractData.getString(ContractEnum.NAME.getAttr());
        Long signTime = contractData.getLong(ContractEnum.SIGN_TIME.getAttr());
        String signTimeShow = "";
        if (Objects.nonNull(signTime)) {
            if (isDateTime){
                String signTimeStr = DateTimeUtil.getStringEpochSecond(signTime, DateTimeUtil.SDFYMDHM);
                signTimeShow = signTimeStr == null ? "--" : signTimeStr;
            }else {
                String signTimeStr = DateTimeUtil.getStringEpochSecond(signTime, DateTimeUtil.SDFDate);
                signTimeShow = signTimeStr == null ? "--" : signTimeStr;
            }
        }
        if (Objects.equals(formDataGetDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
            String status="";
            //LOG.info("合同状态"+contractData.getString(ContractEnum.STATUS.getAttr()));
            if (Objects.nonNull(OrderStatusEnum.getByCode(contractData.getString(OrderEnum.STATUS.getAttr())))){
                status = OrderStatusEnum.getByCode(contractData.getString(OrderEnum.STATUS.getAttr())).getName();
            }else if(StringUtil.isNotEmpty(contractData.getString(OrderEnum.STATUS.getAttr()))){
                status =OrderStatusEnum.PENDING_ORDER_REVIEW.getName();
            }
            String linkDistributor= contractData.getString(ContractEnum.LINK_CUSTOMER_HIDE.getAttr());
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.ORDER_NO.getAttrName(), contractDataEntity.getSerialNo()));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.LINK_DISTRIBUTOR.getAttrName(), linkDistributor));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.SIGN_TIME.getAttrName(), signTimeShow));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.STATUS.getAttrName(), status));
            if (mainUserListStr.length() > 0 ){
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.OWNER_ID.getAttrName(),mainUserListStr));
            }else {
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.OWNER_ID.getAttrName(),userIdAndNameMap.get(ownerId) == null ? "":userIdAndNameMap.get(ownerId)));
            }
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.MINOR_USER.getAttrName(), coUserListStr));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.CREATOR_ID.getAttrName(), userIdAndNameMap.get(creatorId) == null ? "" : userIdAndNameMap.get(creatorId)));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.ADD_TIME.getAttrName(), addTimeShow));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, OrderEnum.UPDATE_TIME.getAttrName(), updateTimeShow));
        } else {
            String status="";
            //LOG.info("合同状态"+contractData.getString(ContractEnum.STATUS.getAttr()));
            if (Objects.nonNull(ContractStatusEnum.getByCode(contractData.getString(ContractEnum.STATUS.getAttr())))){
                status = ContractStatusEnum.getByCode(contractData.getString(ContractEnum.STATUS.getAttr())).getName();
            }else if(StringUtil.isNotEmpty(contractData.getString(ContractEnum.STATUS.getAttr()))){
                status =ContractStatusEnum.SIGNING.getName();
            }
            String linkCustomer = contractData.getString(ContractEnum.LINK_CUSTOMER_HIDE.getAttr());
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.CONTRACT_NO.getAttrName(), contractDataEntity.getSerialNo()));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.LINK_CUSTOMER.getAttrName(), linkCustomer));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.SIGN_TIME.getAttrName(), signTimeShow));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.STATUS.getAttrName(), status));
            if (mainUserListStr.length() > 0 ){
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.OWNER_ID.getAttrName(),mainUserListStr));
            }else {
                explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.OWNER_ID.getAttrName(),userIdAndNameMap.get(ownerId) == null ? "":userIdAndNameMap.get(ownerId)));
            }
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.MINOR_USER.getAttrName(), coUserListStr));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.CREATOR_ID.getAttrName(), userIdAndNameMap.get(creatorId) == null ? "" : userIdAndNameMap.get(creatorId)));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.ADD_TIME.getAttrName(), addTimeShow));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, ContractEnum.UPDATE_TIME.getAttrName(), updateTimeShow));

        }
            appListPojos.add(new AppListPojo(contractDataEntity.getId(), contractName, explains, null, null, others));
        }

        ListAppVO listAppVO = new ListAppVO();
        listAppVO.setList(appListPojos);
        listAppVO.setTotalCount(1);
        return listAppVO;
    }

    public List<FieldAttrEntity> handleWaitPurchaseDetailHead(boolean isEnglish) {
        List<FieldAttrEntity> list = new ArrayList<>();
        // 时间
        FieldAttrEntity dateField = new FieldAttrEntity();
        dateField.setAttr("date");
        dateField.setAttrName("时间");
        dateField.setFieldType(FieldTypeEnum.DATETIME.getType());
        dateField.setVisible(1);
        dateField.setDateType(DateTypeEnum.YMD.getAlias());
        // 采购合同单号
        FieldAttrEntity purchaseNoField = new FieldAttrEntity();
        purchaseNoField.setAttr("purchaseNo");
        purchaseNoField.setAttrName("采购合同编号");
        purchaseNoField.setFieldType(FieldTypeEnum.SERIALNO.getType());
        purchaseNoField.setVisible(1);
        // 采购合同名称
        FieldAttrEntity purchaseNameField = new FieldAttrEntity();
        purchaseNameField.setAttr("purchaseName");
        purchaseNameField.setAttrName("采购合同名称");
        purchaseNameField.setFieldType(FieldTypeEnum.TEXT.getType());
        purchaseNameField.setVisible(1);
        // 已采购数量
        FieldAttrEntity purchaseNumField = new FieldAttrEntity();
        purchaseNumField.setAttr("purchaseNum");
        purchaseNumField.setAttrName("已采购数量");
        purchaseNumField.setFieldType(FieldTypeEnum.NUM.getType());
        purchaseNumField.setVisible(1);
        // 已入库数量
        FieldAttrEntity instockNumField = new FieldAttrEntity();
        instockNumField.setAttr("instockNum");
        instockNumField.setAttrName("已入库数量");
        instockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        instockNumField.setVisible(1);
        // 销售出库单号
        FieldAttrEntity contractOutstockNoField = new FieldAttrEntity();
        contractOutstockNoField.setAttr("contractOutstockNo");
        contractOutstockNoField.setAttrName("销售出库单号");
        contractOutstockNoField.setFieldType(FieldTypeEnum.SERIALNO.getType());
        contractOutstockNoField.setVisible(1);
        // 出库数量
        FieldAttrEntity outstockNumField = new FieldAttrEntity();
        outstockNumField.setAttr("outstockNum");
        outstockNumField.setAttrName("出库数量");
        outstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        outstockNumField.setVisible(1);
        // 未出库数量
        FieldAttrEntity waitOutstockNumField = new FieldAttrEntity();
        waitOutstockNumField.setAttr("waitOutstockNum");
        waitOutstockNumField.setAttrName("未出库数量");
        waitOutstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        waitOutstockNumField.setVisible(1);
        // 建议采购量
        FieldAttrEntity advisePurchaseNumField = new FieldAttrEntity();
        advisePurchaseNumField.setAttr("advisePurchaseNum");
        advisePurchaseNumField.setAttrName("建议采购量");
        advisePurchaseNumField.setFieldType(FieldTypeEnum.NUM.getType());
        advisePurchaseNumField.setVisible(1);
        if (isEnglish){
            advisePurchaseNumField.setAttrName("advisePurchaseNum");
            dateField.setAttrName("date");
            purchaseNoField.setAttrName("purchaseNo");
            purchaseNameField.setAttrName("purchaseName");
            purchaseNumField.setAttrName("purchaseNum");
            instockNumField.setAttrName("instockNum");
            contractOutstockNoField.setAttrName("contractOutstockNo");
            outstockNumField.setAttrName("outstockNum");
            waitOutstockNumField.setAttrName("waitOutstockNum");
        }
        list.add(dateField);
        list.add(purchaseNoField);
        list.add(purchaseNameField);
        list.add(purchaseNumField);
        list.add(instockNumField);
        list.add(contractOutstockNoField);
        list.add(outstockNumField);
        list.add(waitOutstockNumField);
        list.add(advisePurchaseNumField);
        return list;
    }

    public List<FieldAttrEntity> handleWaitProductHead(boolean isDingTalk,boolean isEnglish) {
        // 暂时按照之前逻辑写死表头
        List<FieldAttrEntity> list = new ArrayList<>();


        // 表头字段
        // 产品图片 产品名称 产品编号 规格  销售单位(合同订单单位) 供应商 备注
        // 销售数量 已采购数量 已入库数量 出库数量 未出库数量 建议采购量
        // 以销定购明细 库存查询

        // 产品图片
        FieldAttrEntity productImgsField = new FieldAttrEntity();
        productImgsField.setAttr(ProductEnum.PRODUCT_IMGS.getSaasAttr());
        productImgsField.setAttrName(ProductEnum.PRODUCT_IMGS.getAttrName());
        productImgsField.setFieldType(ProductEnum.PRODUCT_IMGS.getFieldType());
        productImgsField.setVisible(1);
        list.add(productImgsField);
        // 产品名称
        FieldAttrEntity productNameField = new FieldAttrEntity();
        productNameField.setAttr(ProductEnum.NAME.getSaasAttr());
        productNameField.setAttrName(ProductEnum.NAME.getAttrName());
        productNameField.setFieldType(ProductEnum.NAME.getFieldType());
        productNameField.setVisible(1);
        list.add(productNameField);
        // 产品编号
        FieldAttrEntity productNoField = new FieldAttrEntity();
        productNoField.setAttr(ProductEnum.SERIALNO.getSaasAttr());
        productNoField.setAttrName(ProductEnum.SERIALNO.getAttrName());
        productNoField.setFieldType(ProductEnum.SERIALNO.getFieldType());
        productNoField.setVisible(1);
        list.add(productNoField);
        // 产品规格
        FieldAttrEntity productSpecField = new FieldAttrEntity();
        productSpecField.setAttr(ProductEnum.SPECIFICATION.getSaasAttr());
        productSpecField.setAttrName(ProductEnum.SPECIFICATION.getAttrName());
        productSpecField.setFieldType(ProductEnum.SPECIFICATION.getFieldType());
        productSpecField.setVisible(1);
        list.add(productSpecField);
        // 销售单位
        FieldAttrEntity productUnitField = new FieldAttrEntity();
        productUnitField.setAttr("productUnit");
        productUnitField.setSaasAttr(ProductEnum.UNIT.getSaasAttr());
        productUnitField.setAttrName(ContractProductEnum.UNIT.getAttrName());
        productUnitField.setFieldType(ContractProductEnum.UNIT.getFieldType());
        productUnitField.setVisible(1);
        list.add(productUnitField);
        // 供应商
        FieldAttrEntity productSupplierField = new FieldAttrEntity();
        productSupplierField.setAttr(ProductEnum.SUPPLIER.getSaasAttr());
        productSupplierField.setAttrName(ProductEnum.SUPPLIER.getAttrName());
        productSupplierField.setFieldType(ProductEnum.SUPPLIER.getFieldType());
        productSupplierField.setVisible(1);
        list.add(productSupplierField);
        // 备注
        FieldAttrEntity productMemoField = new FieldAttrEntity();
        productMemoField.setAttr(ContractProductEnum.MEMO.getSaasAttr());
        productMemoField.setAttrName(ContractProductEnum.MEMO.getAttrName());
        productMemoField.setFieldType(ContractProductEnum.MEMO.getFieldType());
        productMemoField.setVisible(1);
        list.add(productMemoField);
        // 销售数量
        FieldAttrEntity marketNumField = new FieldAttrEntity();
        marketNumField.setAttr("marketNum");
        marketNumField.setAttrName("销售数量");
        marketNumField.setFieldType(FieldTypeEnum.NUM.getType());
        marketNumField.setVisible(1);
        // 已采购数量
        FieldAttrEntity purchaseNumField = new FieldAttrEntity();
        purchaseNumField.setAttr("purchaseNum");
        purchaseNumField.setAttrName("已采购数量");
        purchaseNumField.setFieldType(FieldTypeEnum.NUM.getType());
        purchaseNumField.setVisible(1);
        // 已入库数量
        FieldAttrEntity instockNumField = new FieldAttrEntity();
        instockNumField.setAttr("instockNum");
        instockNumField.setAttrName("已入库数量");
        instockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        instockNumField.setVisible(1);
        // 出库数量
        FieldAttrEntity outstockNumField = new FieldAttrEntity();
        outstockNumField.setAttr("outstockNum");
        outstockNumField.setAttrName("出库数量");
        outstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        outstockNumField.setVisible(1);
        // 未出库数量
        FieldAttrEntity waitOutstockNumField = new FieldAttrEntity();
        waitOutstockNumField.setAttr("waitOutstockNum");
        waitOutstockNumField.setAttrName("未出库数量");
        waitOutstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        waitOutstockNumField.setVisible(1);
        // 建议采购量
        FieldAttrEntity advisePurchaseField = new FieldAttrEntity();
        advisePurchaseField.setAttr("advisePurchaseNum");
        advisePurchaseField.setAttrName("建议采购量");
        advisePurchaseField.setFieldType(FieldTypeEnum.NUM.getType());
        advisePurchaseField.setVisible(1);
        advisePurchaseField.setEditable(1);
        // 以销定购明细
        FieldAttrEntity purchaseDetailField = new FieldAttrEntity();
        purchaseDetailField.setAttr("purchaseDetail");
        purchaseDetailField.setAttrName("以销定购明细");
        purchaseDetailField.setFieldType(FieldTypeEnum.WAIT_PURCHASE_DETAIL.getType());
        purchaseDetailField.setEditable(1);
        // 库存查询
        FieldAttrEntity stockSearchField = new FieldAttrEntity();
        stockSearchField.setAttr("stockSearch");
        stockSearchField.setAttrName("库存查询");
        stockSearchField.setFieldType(FieldTypeEnum.WAIT_PURCHASE_DETAIL.getType());
        stockSearchField.setEditable(1);
        if (isEnglish){
            stockSearchField.setAttrName("stockSearch");
            marketNumField.setAttrName("marketNum");
            purchaseNumField.setAttrName("purchaseNum");
            outstockNumField.setAttrName("outstockNum");
            instockNumField.setAttrName("instockNum");
            waitOutstockNumField.setAttrName("waitOutstockNum");
            purchaseDetailField.setAttrName("purchaseDetail");
            advisePurchaseField.setAttrName("advisePurchaseNum");
        }
        list.add(marketNumField);
        list.add(purchaseNumField);
        list.add(instockNumField);
        list.add(outstockNumField);
        list.add(waitOutstockNumField);
        if (isDingTalk) {
            list.add(4, advisePurchaseField);
        } else {
            list.add(advisePurchaseField);
        }
        list.add(purchaseDetailField);
        list.add(stockSearchField);
        return list;
    }

    @Override
    public PaasFormDataEsListVO statement(FormDataListDTO formDataListDTO) throws XbbException {
        if (!Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
        Optional<ConditionsEntityExt> first = conditionList.stream().filter(item -> Objects.equals(item.getFieldType(), FieldTypeEnum.CHECK_DATE.getType())).findFirst();
        if (first.isPresent()) {
            // 对账日期的范围筛选
            ConditionsEntityExt conditionsEntityExt = first.get();
            ConditionsEntityExt startCondition = new ConditionsEntityExt();
            BeanUtil.copyProperties(conditionsEntityExt, startCondition);
            startCondition.setAttr(startCondition.getAttr() + ".startTime");
            ConditionsEntityExt endCondition = new ConditionsEntityExt();
            BeanUtil.copyProperties(conditionsEntityExt, endCondition);
            endCondition.setAttr(endCondition.getAttr() + ".endTime");
            conditionList.add(startCondition);
            conditionList.add(endCondition);
            conditionList.remove(conditionsEntityExt);
        }
        conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(),formDataListDTO.getCorpid(),formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        saasListDataPermissionHelp.listDataPermission(conditionList,formDataListDTO.getLoginUser(),XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode(), formDataListDTO.getSubBusinessType());
        // app端筛选筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionList,userEntity,XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        formDataListDTO.setConditions(conditionList);
        return paasFormDataService.listByEs(formDataListDTO);
    }

    /**
     * 设置范围筛选
     *
     * @param nearCustomerDTO
     * @param conditionList
     * @throws XbbException
     * @author long.rao
     * @date 2020-03-03 15:54
     */
    private void rangeScreen(NearCustomerDTO nearCustomerDTO, List<ConditionsEntityExt> conditionList) throws XbbException {
        if (Objects.equals(nearCustomerDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            // 范围筛选仅支持web端
            return;
        }
        JSONObject rangeScreen = nearCustomerDTO.getRangeScreen();
        if (Objects.isNull(rangeScreen) || Objects.isNull(rangeScreen.get(RangeScreenConstant.TYPE)) || StringUtil.isEmpty(rangeScreen.getString(RangeScreenConstant.TYPE)) || Objects.isNull(rangeScreen.get(RangeScreenConstant.VALUE))) {
            return;
        }

        String type;
        List<String> values;
        String attr;
        try {
            type = rangeScreen.getString(RangeScreenConstant.TYPE);
            values = rangeScreen.getJSONArray(RangeScreenConstant.VALUE).toJavaList(String.class);
            attr = rangeScreen.getString(RangeScreenConstant.ATTR);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), "saasListHelp.commonFilter中的commonFilter参数错误");
        }
        if (CollectionsUtil.isEmpty(values)) {
            return;
        }
        if (Objects.equals(type, RangeScreenConstant.DEPARTMENT)) {
            List<Long> deptIds = new ArrayList<>(values.size());
            values.forEach(item -> deptIds.add(Long.valueOf(item)));
            values = userModel.getUserIdsRecursionDep(deptIds, nearCustomerDTO.getCorpid(), 1, true);
        }
        Integer fieldType = 0;
        if (Objects.equals(attr, CustomerManagementEnum.OWNER_ID.getAttr())) {
            fieldType = CustomerManagementEnum.OWNER_ID.getFieldType();
        } else if (Objects.equals(attr, CustomerManagementEnum.COUSERID.getAttr())) {
            fieldType = CustomerManagementEnum.COUSERID.getFieldType();
        } else if (Objects.equals(attr, CustomerManagementEnum.CREATOR_ID.getAttr())) {
            fieldType = CustomerManagementEnum.CREATOR_ID.getFieldType();
        }
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(attr, "", fieldType, ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
        conditionList.add(conditionsEntityExt);
    }

    private PaasFormDataEsListVO productListSuperByIndex(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO = productAnalysisDataHandle.analysisDataByIndex(formDataListDTO);
        boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
        if (notExport){
            paasFormDataEsListVO.setExplainMap(new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
        }
        return paasFormDataEsListVO;
    }

    private void handleConditionBySubBusinessType(FormDataListDTO formDataListDTO, List<ConditionsEntityExt> conditionList) {
        // 由于图表那边也调用这个方法，所以有些特殊逻辑
        if (!Objects.equals(formDataListDTO.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
            conditionList.addAll(saasListHelp.packageConditionBySubBusinessType(formDataListDTO.getSubBusinessType(), formDataListDTO.getCorpid(), formDataListDTO.getUserId(), formDataListDTO.getStatusFilter()));
        }
    }

    private Map<String, Object> getPurchaseProductParam(FormDataListDTO formDataListDTO) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try{
            param.put("corpid", formDataListDTO.getCorpid());
            param.put("start",(formDataListDTO.getPage()-1)*formDataListDTO.getPageSize());
            param.put("pageNum",formDataListDTO.getPageSize());
            //获得二级筛选条件和有可见权限的userId
            saasListHelp.getWaitInstockProductFilter(formDataListDTO, param);
            //获得排序与模糊查询条件
            saasListHelp.getWaitInstockColumn(formDataListDTO, param);
            //获得进入待入库中，未完全入库的关闭的合同
            saasListHelp.getWaitInstockPurchaseId(formDataListDTO, param);
            //获得导出合同和产品对应条件
            saasListHelp.getWaitInstockImportParam(formDataListDTO, param);
        }catch (Exception e){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100071,MessageConstant.WAITINSTOCK_PARAM_MISTAKE);
        }
        return param;
    }


    @Override
    public ListAppVO formatWaitPurchaseInstockDetail(FormDataGetDTO formDataGetDTO) throws XbbException {
        List<AppListPojo> appListPojos = new ArrayList<>();
        String corpid = formDataGetDTO.getCorpid();
        Long purchaseId=formDataGetDTO.getDataId();
        Long linkId = formDataGetDTO.getLinkId();
        //封装采购合同查询参数
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), purchaseId));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PURCHASE.getType()));
        XbbAggregatedPage<PaasFormDataEntity> esEntities = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_PURCHASE, boolQueryBuilder, PaasFormDataEntity.class, Arrays.asList(FieldTypeEnum.DATAID.getAlias(), FieldTypeEnum.SERIALNO.getAlias(),"data",FieldTypeEnum.ADDTIME.getAlias(), FieldTypeEnum.OWNERID.getAlias(), FieldTypeEnum.CREATORID.getAlias()), 1, 1, null);
        //获取采购合同ES数据
        PaasFormDataEntity purchaseDataEntity = esEntities.getContent().get(0);
        JSONObject purchaseData = purchaseDataEntity.getData();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("purchaseSheetId", purchaseId);
        param.put("id", linkId);
        //获取合同产品信息
        List<PurchaseProductEntity> purchaseProductEntityList = purchaseProductModel.findEntitys(param);
        //获得入库产品信息
        List<InstockProductEntity> instockProductEntityList = instockProductModel.getInstockProductByRefId(param);
        Map<Long, Double> instockProduct = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        instockProductEntityList.forEach(instockProductEntity -> {
            Double num = instockProduct.get(instockProductEntity.getRefProductId());
            if(Objects.nonNull(num)){
                num = num + instockProductEntity.getProductNum();
            }else {
                num = instockProductEntity.getProductNum();
            }
            instockProduct.put(instockProductEntity.getRefProductId(), num);
        });
        purchaseProductEntityList.forEach(purchaseProductEntity -> {
            Double num = instockProduct.get(purchaseProductEntity.getId());
            if (Objects.nonNull(num)){
                purchaseProductEntity.setInstockNum(num);
            }
        });
        //对权限进行处理
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PURCHASE.getCode(),formDataGetDTO.getCorpid());
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        processPurchaseAndproductExplain(explainList, purchaseDataEntity, purchaseProductEntityList, formDataGetDTO);
        List<WaitOutstockProductPojo> waitOutstockProductPojoList = getWaitData(formDataGetDTO,purchaseProductEntityList);
        JSONArray explains = new JSONArray();
        JSONObject others = new JSONObject();
        String purchaseName = FastJsonHelper.getStringOrDefault(purchaseData, PurchaseEnum.PURCHASE_NAME.getAttr(), "");
        String purchaseSerialNo = purchaseDataEntity.getSerialNo();
        String supplierName = purchaseData.getString(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr());
        Long signTime = purchaseData.getLong(PurchaseEnum.SIGN_TIME.getAttr());
        Long arriveTime = purchaseData.getLong(PurchaseEnum.ESTIMATE_ARRIVE_TIME.getAttr());
        String status = purchaseData.getString(PurchaseEnum.STATUS.getAttr());
        String statusName = "";
        if(Objects.nonNull(status) && !Objects.equals(status, "")){
            statusName = PurchaseStatusEnum.getName(status);
        }
        String signerId = purchaseData.getString(PurchaseEnum.SIGNER_ID.getAttr());
        UserEntity userEntity = userModel.getByKeyIngoreDel(signerId,corpid);
        String signerName = "";
        if (Objects.nonNull(userEntity)){
            signerName = userEntity.getName();
        }
        String signTimes = "";
        String arriveTimes = "";
        for (FieldAttrEntity item: explainList) {
            if (Objects.equals(item.getAttr(), PurchaseEnum.SIGN_TIME.getAttr())) {
                signTimes = signTime == null ? "" : DateTimeUtil.getStringEpochSecond(signTime, item.getDateType());
            } else if (Objects.equals(item.getAttr(), PurchaseEnum.ESTIMATE_ARRIVE_TIME.getAttr())) {
                arriveTimes = arriveTime == null ? "" : DateTimeUtil.getStringEpochSecond(arriveTime, item.getDateType());
            }
        }
        Long addTime = purchaseDataEntity.getAddTime();
        String addTimes = addTime == null ? "" : DateTimeUtil.getStringEpochSecond(addTime, DateTimeUtil.SDFYMDHM);
        if (Objects.equals(formDataGetDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE.getCode())){
            List<WaitOutProductDTO> waitOutProductDTOs = new ArrayList<>();
            for (WaitOutstockProductPojo waitOutstockProductPojo : waitOutstockProductPojoList){
                JSONArray products = new JSONArray();
                WaitOutProductDTO waitOutProductDTO = new WaitOutProductDTO();
                List<UnitItemPoJo> transformUnitRate = waitOutstockProductPojo.getTransformUnitRate() == null ? new ArrayList<>() : waitOutstockProductPojo.getTransformUnitRate();
                Integer enableMultiUnit = waitOutstockProductPojo.getEnableMultiUnit() == null ? 0 : waitOutstockProductPojo.getEnableMultiUnit();
                products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitInstockEnum.PRODUCT_NO.getAttrName(),waitOutstockProductPojo.getProductNo()));
                products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitInstockEnum.SPECIFICATION.getAttrName(),waitOutstockProductPojo.getSpecification()));
                products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitInstockEnum.UNIT.getAttrName(),waitOutstockProductPojo.getUnit()));
                products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitInstockEnum.STOCK.getAttrName(),waitOutstockProductPojo.getNum()));
                products.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitInstockEnum.MEMO.getAttrName(),waitOutstockProductPojo.getMemo()));
                waitOutProductDTO.setProductId(waitOutstockProductPojo.getId());
                waitOutProductDTO.setProductImage(waitOutstockProductPojo.getProductThumnail());
                waitOutProductDTO.setProductName(waitOutstockProductPojo.getProductName());
                waitOutProductDTO.setTransformUnitRate(transformUnitRate);
                waitOutProductDTO.setProductInfo(products);
                waitOutProductDTO.setEnableMultiUnit(enableMultiUnit);
                waitOutProductDTO.setBusinessUnit(waitOutstockProductPojo.getBusinessUnit());
                waitOutProductDTO.setLinkId(waitOutstockProductPojo.getId());
                waitOutProductDTOs.add(waitOutProductDTO);
            }
            others.put("waitStockProcduct",waitOutProductDTOs);
            others.put("formId",purchaseDataEntity.getFormId());
            others.put("menuId",purchaseDataEntity.getMenuId());
            others.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.PURCHASE.getCode());
            others.put(StringConstant.DATA_ID, purchaseDataEntity.getDataId());
            others.put("sourceBusinessType", XbbRefTypeEnum.PRODUCT.getCode());
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitInstockEnum.SHEET_NO.getAttrName(),purchaseSerialNo));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,WaitInstockEnum.SUPPLIER_ID.getAttrName(),supplierName));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.SIGN_TIME.getAttrName(),signTimes));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.ESTIMATE_ARRIVE_TIME.getAttrName(),arriveTimes));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.STATUS.getAttrName(),statusName));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.SIGNER_ID.getAttrName(),signerName));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.ADD_TIME.getAttrName(),addTimes));
            appListPojos.add(new AppListPojo(purchaseDataEntity.getDataId(), purchaseName  , explains, others));
        }else if (Objects.equals(formDataGetDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            WaitOutstockProductPojo waitOutstockProductPojo = waitOutstockProductPojoList.get(0);
            List<UnitItemPoJo> transformUnitRate = waitOutstockProductPojo.getTransformUnitRate() == null ? new ArrayList<>() : waitOutstockProductPojo.getTransformUnitRate();
            Integer enableMultiUnit = waitOutstockProductPojo.getEnableMultiUnit() == null ? 0 : waitOutstockProductPojo.getEnableMultiUnit();
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitInstockEnum.SPECIFICATION.getAttrName(), waitOutstockProductPojo.getSpecification()));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitInstockEnum.SHEET_NO.getAttrName(),purchaseSerialNo));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitInstockEnum.SUPPLIER_ID.getAttrName(),supplierName));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitInstockEnum.STOCK.getAttrName(), waitOutstockProductPojo.getNum()));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitInstockEnum.PRODUCT_NO.getAttrName(), waitOutstockProductPojo.getProductNo()));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitInstockEnum.UNIT.getAttrName(), waitOutstockProductPojo.getUnit()));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitInstockEnum.MEMO.getAttrName(), waitOutstockProductPojo.getMemo()));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW, WaitInstockEnum.PURCHASE_NAME.getAttrName(),purchaseName));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.STATUS.getAttrName(),statusName));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.ESTIMATE_ARRIVE_TIME.getAttrName(),arriveTimes));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.SIGNER_ID.getAttrName(),signerName));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.SIGN_TIME.getAttrName(),signTimes));
            explains.add(String.format(StringConstant.APP_LIST_VALUE_SHOW,PurchaseEnum.ADD_TIME.getAttrName(),addTimes));
            others.put("formId",purchaseDataEntity.getFormId());
            others.put("menuId",purchaseDataEntity.getMenuId());
            others.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.PURCHASE.getCode());
            others.put(StringConstant.DATA_ID, purchaseDataEntity.getDataId());
            others.put("transformUnitRate", transformUnitRate);
            others.put("enableMultiUnit",enableMultiUnit);
            others.put("sourceBusinessType", XbbRefTypeEnum.PRODUCT.getCode());
            others.put(WaitInstockEnum.PRODUCT_NAME.getAttr(),waitOutstockProductPojo.getProductName());
            others.put("productId",waitOutstockProductPojo.getId());
            others.put("linkId",waitOutstockProductPojo.getId());
            others.put("productImage",waitOutstockProductPojo.getProductThumnail());
            others.put("businessUnit", waitOutstockProductPojo.getBusinessUnit());
            appListPojos.add(new AppListPojo(purchaseDataEntity.getDataId(), waitOutstockProductPojo.getProductName()  , explains, others));
        }
        ListAppVO listAppVO = new ListAppVO();
        listAppVO.setList(appListPojos);
        listAppVO.setTotalCount(1);
        return listAppVO;
    }

    public List<WaitOutstockProductPojo> getWaitData(FormDataGetDTO formDataGetDTO , List<PurchaseProductEntity> purchaseProductEntityList) throws XbbException {
        String corpid = formDataGetDTO.getCorpid();
        List<WaitOutstockProductPojo> waitOutstockProductPojoList = new ArrayList<>();
        Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> productIdSet = new HashSet<>();
        for (PurchaseProductEntity entity : purchaseProductEntityList) {
            productIdSet.add(entity.getProductId());
        }
        Map<Long, ProductEntityExt> productMap1 = saasListHelp.getProductMap(productIdSet, corpid);
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
        productItems.forEach(item -> unitItemMap.put(item.getValue().toString(), item.getText()));
        for (PurchaseProductEntity entity : purchaseProductEntityList) {
            Double num = Arith.sub(entity.getProductNum(), entity.getInstockNum());
            if(Objects.equals(num.compareTo(BasicConstant.ZERO_DOUBLE), 0) && Objects.equals(formDataGetDTO.getBusinessType(), XbbRefTypeEnum.PURCHASE.getCode())){
                continue;
            }
            String unit = entity.getProductUnit();
            entity.setWaitInstockNum(num);
            WaitOutstockProductPojo waitOutstockProductPojo = new WaitOutstockProductPojo();
            saasListHelp.setProductThumnail(waitOutstockProductPojo, productMap1, entity.getProductId());
            waitOutstockProductPojo.setProductName(entity.getProductName());
            waitOutstockProductPojo.setProductNo(entity.getProductNo());
            saasListHelp.setSpecification(waitOutstockProductPojo, productMap1, entity.getProductId());
            waitOutstockProductPojo.setId(entity.getId());
            waitOutstockProductPojo.setNum(entity.getWaitInstockNum());
            waitOutstockProductPojo.setMemo(entity.getMemo());
            if(Objects.isNull(unit)){
                waitOutstockProductPojo.setUnit("");
            }else {
                waitOutstockProductPojo.setUnit(unitItemMap.getOrDefault(unit, ""));
            }
            // 多单位
            ProductEntityExt productEntityExt = productMap1.get(entity.getProductId());
            if (productEntityExt != null) {
                JSONObject productData = productEntityExt.getData();
                if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                    JSONObject businessUnit = new JSONObject();
                    businessUnit.put("text", unitItemMap.getOrDefault(entity.getBusinessUnit().toString(), ""));
                    businessUnit.put("value", entity.getBusinessUnit());
                    if(Objects.nonNull(unit)){
                        waitOutstockProductPojo.setUnit(unitItemMap.getOrDefault(entity.getBusinessUnit().toString(), ""));
                    }
                    waitOutstockProductPojo.setNum(Arith.div(num, entity.getRate()));
                    waitOutstockProductPojo.setBusinessUnit(businessUnit);
                    Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                    waitOutstockProductPojo.setTransformUnitRate(groupItemsMap.get(productUnit));
                    waitOutstockProductPojo.setEnableMultiUnit(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                    if ((!StringUtil.isDigital(unit) || Long.parseLong(unit) < ProductConstant.MAX_SINGLE_UNIT_VALUE) && Objects.nonNull(unit)) {
                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                        waitOutstockProductPojo.setUnit(multiUnitItemPoJo != null ? multiUnitItemPoJo.getBaseName() : waitOutstockProductPojo.getUnit());
                    }
                }
            }
            waitOutstockProductPojoList.add(waitOutstockProductPojo);
        }
        return waitOutstockProductPojoList;
    }
    @Override
    public PaasFormDataEsListVO smartReplenishment(FormDataListDTO formDataListDTO) throws XbbException{
        // 智能补货权限可见权限
        UserVO loginUser = formDataListDTO.getLoginUser();
        if (!loginUser.getPermSet().contains(ProPermissionAliasEnum.SMART_REPLENISHMENT_VIEW.getAlias())){
            throw new XbbException(PurchaseErrorCodeEnum.API_ERROR_225035);
        }
        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        List<PaasFormDataEntityExt>  paasFormDataESList = new ArrayList<>();
        Integer page = formDataListDTO.getPage() == null ? 1 : formDataListDTO.getPage();
        Integer pageSize = formDataListDTO.getPageSize() == null ? PageConstant.DEFAULT_PAGE_SIZE : formDataListDTO.getPageSize();
        String corpid = formDataListDTO.getCorpid();
        // 获取产品解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        //处理产品解释
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String,FieldAttrEntity> productExplainMap = new HashMap<>();
        if(CollectionsUtil.isNotEmpty(explainList)) {
            explainList.forEach(item -> productExplainMap.put(item.getAttr(), item));
        }
        //表单获取
        PaasFormEntityExt form = formDataListSearchHelp.getForm(formDataListDTO);
        paasFormDataEsListVO.setForm(form);
        /* ==================== 上部按钮权限和下部按钮权限 ==================== */
        formDataListSearchHelp.setButtons(formDataListDTO, paasFormDataEsListVO);
        // 获取公司级配置 拿到该公司下的智能补货公式
        boolean enablePurchasePassage = false;
        boolean enableMiniStock = false;
        // 采购在途公司级配置
        CompanyConfigEntity purchasePassageConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_PURCHASE_PASSAGE.getAlias(), corpid);
        // 最低库存公司级配置
        CompanyConfigEntity miniStockConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_MINI_STOCK.getAlias(), corpid);
        if (Objects.isNull(purchasePassageConfig) || Objects.equals(BasicConstant.IS_USE.toString(),purchasePassageConfig.getConfigValue())){
            enablePurchasePassage = true;
        }
        if (Objects.isNull(miniStockConfig) || Objects.equals(BasicConstant.IS_USE.toString(),miniStockConfig.getConfigValue())){
            enableMiniStock = true;
        }
        List<FieldAttrEntity> headList = saasListHelp.handelSmartReplenishmentHeadList(productExplainMap, enablePurchasePassage , enableMiniStock);
        paasFormDataEsListVO.setHeadList(headList);
        // 从数据库中获取数据
        List<SmartReplenishmentEntity> smartReplenishmentEntityList = saasListHelp.getSmartReplenishmentList(formDataListDTO, enablePurchasePassage , enableMiniStock);
        if (CollectionsUtil.isEmpty(smartReplenishmentEntityList)){
            // 设置分页
            paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(0));
            paasFormDataEsListVO.setPaasFormDataESList(new ArrayList<>());
            // 处理列表页字段排序
            formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
            return paasFormDataEsListVO;
        }
        Integer count = saasListHelp.getSmartReplenishmentCount(formDataListDTO,enablePurchasePassage,enableMiniStock);
        // key=productId  value = 建议采购量
        Map<Long, Double> advisePurchaseNumMap = new HashMap<>();
        List<Long> productIdList = new ArrayList<>();
        List<Long> parentIdList = new ArrayList<>();
        if(CollectionsUtil.isNotEmpty(smartReplenishmentEntityList)){
            smartReplenishmentEntityList.forEach(item -> {
                productIdList.add(item.getProductId());
                parentIdList.add(item.getParentProductId());
                advisePurchaseNumMap.put(item.getProductId(), item.getSumNum());
            });
        }
        // 去产品表中拿数据
        List<ProductEntityExt> productList = productModel.getProductListByIdIn(corpid, productIdList, 0);
        Map<Long, ProductEntityExt> productMap = new HashMap<>();
        if(CollectionsUtil.isNotEmpty(productIdList)){
            productList.forEach(item -> productMap.put(item.getId(),item));
        }

        //供应商 规格数据查询
        Map<Long, List<SupplierProductEntity>> supplierProductByParentIdIn = supplierProductModel.getSupplierProductByParentIdIn(corpid, productIdList, false);
        Map<Long, List<SpecificationEntity>> specificationMap = specificationModel.getSpecificationMap(corpid, parentIdList);
        // 多单位处理
        Map<String, String> unitItemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        List<ItemPoJo> productItems = relativeProductHelp.getBusinessUnitItems(corpid);
        productItems.forEach(item -> {
            if (!Objects.equals(item.getIsOther(), 1)) {
                unitItemMap.put(item.getValue().toString(), item.getText());
            }
        });
        if(CollectionsUtil.isNotEmpty(smartReplenishmentEntityList)){
            for (SmartReplenishmentEntity smartReplenishmentEntity : smartReplenishmentEntityList) {
                Long productId = smartReplenishmentEntity.getProductId();
                ProductEntityExt productEntityExt = productMap.get(productId);
                if (Objects.nonNull(productEntityExt)){
                    JSONObject productData = productEntityExt.getData();
                    if (Objects.nonNull(productData)){
                        JSONObject data = new JSONObject();
                        // data塞入产品数据
                        data.put(ProductEnum.PRODUCT_IMGS.getAttr(),productData.get(ProductEnum.PRODUCT_IMGS.getAttr()));
                        if (CollectionsUtil.isEmpty(productData.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()))) {
                            data.put(ProductEnum.PRODUCT_IMGS.getAttr(), productData.getJSONArray(ProductEnum.THUMBNAIL.getAttr()));
                        }
                        data.put(ProductEnum.NAME.getAttr(),productData.get(ProductEnum.NAME.getAttr()));
                        data.put(ProductEnum.SERIALNO.getAttr(),productEntityExt.getSerialNo());
                        data.put(ProductEnum.CREATOR_ID.getAttr(),productEntityExt.getCreatorId());
                        data.put("ownerId",productEntityExt.getOwnerId());
                        // 规格解析
                        String specStr = specificationModel.joinSpecification(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                        data.put(ProductEnum.SPECIFICATION.getAttr(),specStr);
                        // 供应商解析
                        JSONArray supplierArr = new JSONArray();
                        Map<Long, String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        if (!supplierProductByParentIdIn.isEmpty() && supplierProductByParentIdIn.containsKey(productId)){
                            List<SupplierProductEntity> supplierProductList = supplierProductByParentIdIn.get(productId);
                            for (SupplierProductEntity supplierProductEntity : supplierProductList) {
                                supplierNameMap.put(supplierProductEntity.getSupplierId(), supplierProductEntity.getSupplierName());
                            }
                            for (Map.Entry<Long, String> entry : supplierNameMap.entrySet()) {
                                JSONObject supplierObj = new JSONObject();
                                supplierObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, entry.getKey());
                                supplierObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, entry.getValue());
                                supplierObj.put(StringConstant.BUSINESS_TYPE,XbbRefTypeEnum.SUPPLIER.getCode());
                                supplierObj.put(StringConstant.SAAS_MARK,SaasMarkEnum.SAAS.getCode());
                                supplierArr.add(supplierObj);
                            }
                        }
                        data.put(ProductEnum.SUPPLIER.getAttr(),supplierArr);
                        Object obj = productData.get(ProductEnum.UNIT.getAttr());
                        String unit = "";
                        if(Objects.nonNull(obj)){
                            unit = obj.toString();
                        }
                        data.put(ContractProductEnum.UNIT.getAttr(), unitItemMap.getOrDefault(unit, Objects.nonNull(unit) && (!ItemUtil.isUUID(unit) || !RegexUtil.isOnePositiveInt(unit.toString())) ? unit : ""));
                        if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                            Long productUnit = productData.getLong(ProductEnum.UNIT.getAttr());
                            data.put(ProductConstant.TRANSFORM_UNIT_RATE,groupItemsMap.get(productUnit));
                            data.put("enableMultiUnit",BasicConstant.ONE);
                            if (StringUtil.isDigital(unit) && Long.parseLong(unit) >= ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                                MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productUnit);
                                if (Objects.nonNull(multiUnitItemPoJo)) {
                                    data.put(ContractProductEnum.UNIT.getAttr(),multiUnitItemPoJo.getBaseName());
                                }
                            }
                        }
                        // 未出库数量
                        data.put("waitOutstockNum", smartReplenishmentEntity.getWaitOutstockNum());
                        // 库存数量
                        data.put(ProductEnum.STOCK.getAttr(), productData.getDouble(ProductEnum.STOCK.getAttr()));
                        // 采购在途数量
                        if (enablePurchasePassage){
                            data.put("pendingInstockNum", smartReplenishmentEntity.getPendingInstockNum());
                        }
                        // 最低库存数量
                        if (enableMiniStock){
                            data.put("miniNum", smartReplenishmentEntity.getMiniNum());
                        }
                        // 建议采购量
                        data.put("advisePurchaseNum", smartReplenishmentEntity.getSumNum());
                        // 塞入一键采购按钮
                        List<ButtonPojo> optionList = new ArrayList<>();
                        optionList.add(new ButtonPojo(ListOptionTabEnum.PURCHASE, XbbRefTypeEnum.PURCHASE.getCode()));
                        JSONObject option = new JSONObject();
                        option.put("value", optionList);
                        data.put(ListOptionEnum.OPTION.getAttr(),option);
                        data.put("parentId",productData.getLong(ProductEnum.PARENT_ID.getAttr()));
                        PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                        paasFormDataEntityExt.setData(data);
                        paasFormDataEntityExt.setSourceData(data);
                        paasFormDataEntityExt.setDataId(smartReplenishmentEntity.getProductId());
                        paasFormDataESList.add(paasFormDataEntityExt);
                    }
                }
            }
        }
        // 处理数据可见权限
        SmartReplenishmentCanSeeData(paasFormDataESList,headList,formDataListDTO);
        // 设置分页
        paasFormDataEsListVO.setPageHelper(new PageHelper(page, pageSize).setRowsCount(count));
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        // 处理列表页字段排序
        formDataListSearchHelp.explainFieldSort(formDataListDTO, paasFormDataEsListVO);
        //表单冻结和隐藏列设置（在按钮设置后处理，防止操作列无法冻结和隐藏）
        formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, paasFormDataEsListVO);
        return paasFormDataEsListVO;
    }

    private void SmartReplenishmentCanSeeData(List<PaasFormDataEntityExt> paasFormDataESList,List<FieldAttrEntity> headList,FormDataListDTO formDataGetDTO) throws XbbException{
        Map<String, FieldAttrEntity> productExplainMap = ExplainUtil.getExplainMapByList(headList);
        UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
        userAndDepartmentGetDTO.setLoginUser(formDataGetDTO.getLoginUser());
        userAndDepartmentGetDTO.setUserId(formDataGetDTO.getUserId());
        userAndDepartmentGetDTO.setCorpid(formDataGetDTO.getCorpid());
        UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
        Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
        Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
        ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
        parseSingleRowDataDTO.setExplainMap(productExplainMap);
        parseSingleRowDataDTO.setUserMap(userMap);
        parseSingleRowDataDTO.setDepartmentMap(departmentMap);
        parseSingleRowDataDTO.setLoginUser(formDataGetDTO.getLoginUser());
        parseSingleRowDataDTO.setUserId(formDataGetDTO.getUserId());
        parseSingleRowDataDTO.setCorpid(formDataGetDTO.getCorpid());


        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
            JSONObject data = paasFormDataEntityExt.getData();
            String creatorId = data.getString(ProductEnum.CREATOR_ID.getAttr());
            // 负责人集合
            List<String> ownerIdList = new ArrayList<>();
            ownerIdList.add(creatorId);
            // 协同人集合 产品协同人
            List<String> minorIdList = new ArrayList<>();
            Map<String, Boolean> smartDataCanseeMap = saasListHelp.parseCanseeParam(headList, creatorId,ownerIdList,minorIdList,parseSingleRowDataDTO);
            for (Map.Entry<String, Boolean> stringBooleanEntry : smartDataCanseeMap.entrySet()) {
                String key = stringBooleanEntry.getKey();
                Boolean value = stringBooleanEntry.getValue();
                if (!value){
                    if (Objects.equals(ProductEnum.NAME.getAttr(),key)){
                        data.put(ProductEnum.NAME.getAttr(), "");
                    }else if (Objects.equals(ProductEnum.SERIALNO.getAttr(),key)){
                        data.put(ProductEnum.SERIALNO.getAttr(), "");
                    } else if (Objects.equals(ProductEnum.SPECIFICATION.getAttr(),key)){
                        data.put(ProductEnum.SPECIFICATION.getAttr(), "");
                    } else if (Objects.equals(ProductEnum.PRODUCT_IMGS.getAttr(),key)){
                        data.put(ProductEnum.PRODUCT_IMGS.getAttr(), "");
                    } else if (Objects.equals(ProductEnum.UNIT.getAttr(),key)){
                        data.put(ProductEnum.UNIT.getAttr(), "");
                    } else if (Objects.equals(ProductEnum.SUPPLIER.getAttr(),key)){
                        data.put(ProductEnum.SUPPLIER.getAttr(), "");
                    } else if (Objects.equals(ProductEnum.STOCK.getAttr(),key)){
                        data.put(ProductEnum.STOCK.getAttr(), "");
                    }
                }
            }
        }
    }
    /**
     * 处理待入库移动端详情的数据权限
     */
    private void processPurchaseAndproductExplain(List<FieldAttrEntity> explainList, PaasFormDataEntity purchaseDataEntity, List<PurchaseProductEntity> purchaseProductEntityList, FormDataGetDTO formDataGetDTO) throws XbbException {
        //获取产品字段的解释
        List<FieldAttrEntity> purchaseExplain = new ArrayList<>();
        explainList.forEach(fieldAttrEntity ->{
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, PurchaseEnum.PURCHASE_NAME.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.SHEET_NO.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.SUPPLIER_ID.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.SIGN_TIME.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.ESTIMATE_ARRIVE_TIME.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.STATUS.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.SIGNER_ID.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.ADD_TIME.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.UPDATE_TIME.getAttr())){
                purchaseExplain.add(fieldAttrEntity);
            }else if (Objects.equals(attr, PurchaseEnum.PRODUCT.getAttr())){
                List<FieldAttrEntity> items = (List<FieldAttrEntity>) fieldAttrEntity.getSubForm().getItems();
                items.forEach(fieldAttrEnt -> {
                    if(Objects.equals(fieldAttrEnt.getAttr(),ProductEnum.UNIT.getAttr())){
                        fieldAttrEnt.setAttr(WaitInstockEnum.UNIT.getAttr());
                        fieldAttrEnt.setAttrName(WaitInstockEnum.UNIT.getAttrName());
                        purchaseExplain.add(fieldAttrEnt);
                    }else if(Objects.equals(fieldAttrEnt.getAttr(),SelectProductEnum.MEMO.getAttr())){
                        fieldAttrEnt.setAttr(WaitInstockEnum.MEMO.getAttr());
                        fieldAttrEnt.setAttrName(WaitInstockEnum.MEMO.getAttrName());
                        fieldAttrEnt.setDisableListSort(BasicConstant.ONE);
                        purchaseExplain.add(fieldAttrEnt);
                    }
                });
            }
        });
        //开始处理权限
        Map<String, FieldAttrEntity> expalinMap = ExplainUtil.getExplainMapByList(purchaseExplain);
        UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
        userAndDepartmentGetDTO.setLoginUser(formDataGetDTO.getLoginUser());
        userAndDepartmentGetDTO.setUserId(formDataGetDTO.getUserId());
        userAndDepartmentGetDTO.setCorpid(formDataGetDTO.getCorpid());
        UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
        Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
        Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
        ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
        parseSingleRowDataDTO.setExplainMap(expalinMap);
        parseSingleRowDataDTO.setUserMap(userMap);
        parseSingleRowDataDTO.setDepartmentMap(departmentMap);
        parseSingleRowDataDTO.setLoginUser(formDataGetDTO.getLoginUser());
        parseSingleRowDataDTO.setUserId(formDataGetDTO.getUserId());
        parseSingleRowDataDTO.setCorpid(formDataGetDTO.getCorpid());
        Map<String, Boolean> canSeeMap = saasListHelp.parseCanseeParam(purchaseExplain, purchaseDataEntity.getCreatorId(),Collections.singletonList(purchaseDataEntity.getOwnerId()),new ArrayList<>(),parseSingleRowDataDTO);
        JSONObject data = purchaseDataEntity.getData();
        for (Map.Entry<String, Boolean> stringBooleanEntry : canSeeMap.entrySet()) {
            String key = stringBooleanEntry.getKey();
            Boolean value = stringBooleanEntry.getValue();
            if (!value ){
                if (Objects.equals(key, WaitInstockEnum.SHEET_NO.getAttr())){
                    purchaseDataEntity.setSerialNo("");
                }else if(Objects.equals(key, WaitInstockEnum.PURCHASE_NAME.getAttr())){
                    data.put(PurchaseEnum.PURCHASE_NAME.getAttr(), "");
                }else if(Objects.equals(key, WaitInstockEnum.SUPPLIER_ID.getAttr())){
                    data.put(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr(), "");
                }else if(Objects.equals(key, WaitInstockEnum.SIGN_TIME.getAttr())){
                    data.put(PurchaseEnum.SIGN_TIME.getAttr(), "");
                }else if(Objects.equals(key, WaitInstockEnum.ESTIMATE_ARRIVE_TIME.getAttr())){
                    data.put(PurchaseEnum.ESTIMATE_ARRIVE_TIME.getAttr(), "");
                }else if(Objects.equals(key, WaitInstockEnum.STATUS.getAttr())){
                    data.put(PurchaseEnum.STATUS.getAttr(), "");
                }else if(Objects.equals(key, WaitInstockEnum.SIGNER_ID.getAttr())){
                    data.put(PurchaseEnum.SIGNER_ID.getAttr(), "");
                }else if(Objects.equals(key, WaitInstockEnum.ADDTIME.getAttr())){
                    purchaseDataEntity.setAddTime(null);
                }else if(Objects.equals(key, WaitInstockEnum.UPDATETIME.getAttr())){
                    purchaseDataEntity.setUpdateTime(null);
                }else if(Objects.equals(key, WaitInstockEnum.UNIT.getAttr())){
                    purchaseProductEntityList.forEach(PurchaseProductEntity ->{
                        PurchaseProductEntity.setProductUnit(null);
                    });
                }else if(Objects.equals(key, WaitInstockEnum.MEMO.getAttr())){
                    purchaseProductEntityList.forEach(PurchaseProductEntity ->{
                        PurchaseProductEntity.setMemo("");
                    });
                }
            }
        }
    }
}
